Most performant way of converting int to string

Daniel Kozák via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Dec 22 13:22:49 PST 2015


V Tue, 22 Dec 2015 21:10:54 +0000
rumbu via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com>
napsáno:

> On Tuesday, 22 December 2015 at 20:52:07 UTC, rumbu wrote:
> > On Tuesday, 22 December 2015 at 19:45:46 UTC, Daniel Kozák 
> > wrote:  
> >> V Tue, 22 Dec 2015 18:11:24 +0000
> >> rumbu via Digitalmars-d-learn 
> >> <digitalmars-d-learn at puremagic.com>
> >> napsáno:
> >>  
> >>> 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!  
> >>> 
> >>> Converting numbers to string involves the most expensive 
> >>> known two operations : division and modulus by 10.  
> >>
> >> No, IIRC few months or maybe years I have optimize this so it 
> >> does not use division and modulus  
> >
> > It's using division and modulus, as expected:
> >
> > https://github.com/D-Programming-Language/phobos/blob/master/std/conv.d#L5529
> >
> > If the compiler is smart enough, maybe it will replace this by 
> > well known multiplication trick.  
> 
> Tested it, I was right:
> 
> No optimizations: two divisions, one for the modulus and one for 
> the division itself
> Optimized: multiplication by 0xCCCCCCCD trick.
> 
> http://imgur.com/a/lHeHe
> 
> 

Yes this is expected :).



More information about the Digitalmars-d-learn mailing list