Most performant way of converting int to string

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


V Tue, 22 Dec 2015 18:39:16 +0000
Ivan Kazmenko via Digitalmars-d-learn
<digitalmars-d-learn at puremagic.com> napsáno:

> On Tuesday, 22 December 2015 at 18:11:24 UTC, rumbu 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!  
> >
> > Converting numbers to string involves the most expensive known 
> > two operations : division and modulus by 10.  
> 
> When the base is known in advance, division and modulus can be 
> substituted by a few additions, subtractions and bit shifts.  For 
> example, the Hacker's Delight book has a chapter dedicated to 
> that, as well as a freely available additional chapter 
> (www.hackersdelight.org/divcMore.pdf).
> 
> Does DMD, or Phobos function to!(string), do anything like that?  
> The number of possible bases is not large anyway.  I've heard 
> major C/C++ compilers do that, but have not looked for a proof 
> myself.

Yes, IIRC, all D compilers should be able to change modulus and
division to few additions, subtractions and bit shifts if base is known
at compile time.

And phobos use this:
https://github.com/D-Programming-Language/phobos/pull/1452




More information about the Digitalmars-d-learn mailing list