Too complicated code for generating a random string?

jerro a at a.com
Sat Feb 23 11:08:03 PST 2013


>     string randomString;
>     {
>         auto tmp = new char[](10);
>         foreach(ref char c ; tmp)
>             c = letters[uniform(0, letters.length)];
>         randomString = cast(string)letters;
>     }
>
> All those scope blocks I put in are not mandatory. At the end 
> of the day, it is 4 lines of code. Very efficient, and the 
> intent is crystal clear.

Or you could simply do this:

string randomString = iota(10).map!(_ => letters[uniform(0, 
$)]).array;

It's one line off code and the intent seems crystal clear to me. 
It's also equally efficient. I've benchmark those to pieces of 
code for various values of n with both DMD and GDC, using -O 
-inline -release:

auto tmp = iota(n).map!(_ => letters[uniform(0, $)]).array;

....

auto tmp = new char[](n);
foreach(ref char c ; tmp)
     c = letters[uniform(0, letters.length)];

For n=10 and when compiled with GDC, the first snippet actually 
performed a little bit (about 10%) better, but for larger sizes 
there was no significant difference.


More information about the Digitalmars-d mailing list