Look and think good things about D

bearophile bearophileHUGS at lycos.com
Fri Nov 15 10:40:12 PST 2013


Ary Borenszweig:

> This last version you wrote, compiling it with 
> "-enable-inlining -release -O3", takes 0.054s (please tell me 
> if I'm missing some flags, in Crystal I just used --release). 
> The Crystal version takes 0.031s. I also tried with n=70. In D: 
> 9.265s. In Crystal: 4.863s.

This version is more than twice faster, because group() avoids 
decoding UTF:


void main(in string[] args) {
     import std.stdio, std.conv, std.algorithm, std.array, 
std.string;

     immutable n = (args.length == 2) ? args[1].to!uint : 10;
     if (n == 0)
         return;

     auto seq = ['1'];
     writefln("%2d: n. digits: %d", 1, seq.length);
     foreach (immutable i; 2 .. n + 1) {
         Appender!(typeof(seq)) result;
         foreach (const digit, const count; 
seq.representation.group) {
             result ~= "123"[count - 1];
             result ~= digit;
         }
         seq = result.data;
         writefln("%2d: n. digits: %d", i, seq.length);
     }
}


> I couldn't compile the first version written in D because I get:
>
> Error: pure function '__lambda1' cannot call impure function 
> 'join'

Just remove the "pure" for ldc2.


> However, I'm starting to think that all those immutable, final 
> switches and gotos are useless if they don't give a performance 
> benefit

Adding immutable to variables sometimes helps catch some troubles 
in your code. In a modern language variables should be immutable 
on default, and functions should be pure on default, because the 
default choice should be the faster (if it's equally safe) and 
because when you read code it's simpler to reason on things that 
have less capabilities (like the capability to mutate for a 
value).

Bye,
bearophile


More information about the Digitalmars-d mailing list