Get Character At?

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Wed Apr 25 10:23:50 PDT 2007


Derek Parnell wrote:
> On Wed, 25 Apr 2007 15:52:45 +0200, Frits van Bommel wrote:
> 
>> I think you can change these last two statements to just:
>  ... 
>> So my version is even faster (about 30%), at least on my machine. And 
>> IMHO it's also more readable. No need to know what "stride" is, for example.
> 
> Well, if we were really into a pissing contest, we'd both remove the calls
> to library routines and code it inline, in assembler etc ... but that was

I was just mentioning that you seemed to be over-complicating the code, 
and as a side-benefit the simpler code was faster as well.

> not the point. Daniel's code is another example of 'foreach' not producing
> the best machine code to solve the problem at hand.

Well to be fair, I don't think that's purely the fault of 'foreach' 
implementation problems in this case.
'foreach' is doing genuinely more work in this case. Specifically, the 
foreach loop is decoding all characters up to the one it returns while 
the getCharAt() variants only actually decode the character asked for, 
using no more than the stride of the preceding ones.

What the foreach version does is therefore more like the following:
-----
dchar nthCharacter2(T)(T string, int n)
{
     int curChar = 0;
     for(size_t index = 0 ; index < string.length ; string.decode(index))
     {
         if( curChar == n )
             return string.decode(index);	// return _next_ char
         curChar++;
     }
     return dchar.init;
}
-----
Which is also on the slow side. (Though on DMD this version is still 
faster than the 'foreach' version :( )
The results with this added as well:
=====
urxae at urxae:~/tmp$ dmd -O -release -inline -run test.d
    Derek Parnell:   14416041
Frits van Bommel:    9803830
      Daniel Keep:   37386228
       for-decode:   33767606
urxae at urxae:~/tmp$ gdc -O3 -finline -frelease -o test test.d && ./test
    Derek Parnell:   17267995
Frits van Bommel:   11836242
      Daniel Keep:   21390295
       for-decode:   25339226
=====
("for-decode" is the code above)


More information about the Digitalmars-d-learn mailing list