What is the FASTEST way to convert a decimal type to a string?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
<span style="font-size:medium <span lang="
Hey everyone:
Were dealing with a financial application where speed is the utmost importance; code readability not necessarily so.
We have a C# app thats tapping into a legacy database. The problem is, that database is storing decimals as "strings" because it otherwise doesnt have a field large enough to hold digits that can be 24-25 digits long (and no decimal places).
This application is reading hundreds of millions of these numbers at a time, performing calculations, then writing them back out as string.
Weve been finding that the "ToString()" method is hit during those hundreds of millions of times, and we want to increase performance there.
Problem is we cant think of any way to do it.
We have found the following which *significantly* increased the speed of operations of converting a string to a decimal, but now want a reverse equivalent.
<pre class="prettyprint //######################################################################################
//This Parse method is significantly faster than calling Convert or Parse methods in benchmark tests.
//Looping over 2,000,000 times converting an 8 element string to a decimal took 1/4 - 1/3 the time
//calling this Parse method as opposed to the built in C# conversion/parse methods.
private decimal ConvertStringNumberToDecimal(string s)
{
decimal value = 0;
for (int i = 0; i < s.Length; i++)
{
value = value * 10 + (s - 0);
}
return value;
} //ConvertStringNumberToDecimal[/code]
<br/>
 
 
My basic thoughts are:
1) somehow get the length of the decimal number WITHOUT converting it to string
2) then perhaps convert to a char[] and write out the char[].
Does anyone have any ideas, suggestions, samples?
<span lang="

View the full article
 
Back
Top