Most performant way of converting int to string

Jakob Ovrum via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Dec 23 03:21:32 PST 2015


On Tuesday, 22 December 2015 at 17:23:11 UTC, Andrew Chapman 
wrote:
> On Tuesday, 22 December 2015 at 17:18:16 UTC, cym13 wrote:
>> On Tuesday, 22 December 2015 at 17:15:27 UTC, Andrew Chapman 
>> wrote:
>>> Sorry if this is a silly question but is the to! method from 
>>> the conv library the most efficient way of converting an 
>>> integer value to a string?
>>>
>>> e.g.
>>> string s = to!string(100);
>>>
>>> I'm seeing a pretty dramatic slow down in my code when I use 
>>> a conversion like this (when looped over 10 million 
>>> iterations for benchmarking).
>>>
>>> Cheers!
>>
>> Out of curiosity a slow down compared to what? No conversion 
>> at all?
>
> Yeah, if I include a simple conversion in my loop:
>
>         for({int i; i = 0;} i < num; i++) {
>                 //string s = to!string(i);
>                 Customer c = Customer(i, "Customer", 
> "99998888", i * 2);
>                 string result = objS.serialize(c);
>         }
>
> If I uncomment the "string s" line I'm seeing a 20% increase in 
> running time, which given what's going on the rest of the code 
> is quite surprising.  I've tried compiling with both dmd and 
> ldc2 - it's the same under both.
>
> Cheers.

Dynamic memory allocation is expensive. If the string is 
short-lived, allocate it on the stack:

enum maxDigits = to!string(ulong.max).length;
foreach(i; 0 .. num) {
     char[maxDigits] buffer = void;
     auto c = Customer(sformat(buffer[], "%s", i));
     string result = objS.serialize(c);
}

Note that this is unsafe if the string (sformat's return value) 
outlives the loop iteration, as this is `buffer`'s scope.


More information about the Digitalmars-d-learn mailing list