Efficiency of immutable vs mutable

TheFlyingFiddle via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 2 20:08:07 PST 2015


On Tuesday, 3 November 2015 at 03:16:07 UTC, Andrew wrote:
> I've written a short D program that involves many lookups into 
> a static array. When I make the array immutable the program 
> runs faster.  This must mean that immutable is more than a 
> restriction on access, it must affect the compiler output. But 
> why and how?
>
> Thanks
> Andrew

I'm going to speculate a bit here since you did not post any code.

Say you have this code:

static char[4] lookup = ['a', 't', 'g', 'c']

This lookup table will be in thread local storage (tls). TLS is a 
way to have global variables that are not shared between threads 
that is every thread has it's own copy of the variable. TLS 
variables are not as fast to access as true global variables 
however since the accessing code has to do some additional lookup 
based on the thread to gain access to the correct copy.

If you change the above code to this:
static immutable char[4] lookup = ['a', 't', 'g', 'c'];

Then you get an immutable array. Since this array cannot change 
and is the same on all threads there is no reason to have 
separate storage for each thread. Thus the above code will create 
a true global variable that is shared between the threads. So 
what you are likely seeing is that a variable changed from being 
tls to being a shared global. Global accessing is faster then TLS 
accessing so this is probably what made your code run faster.

If you want a shared global that is not immutable you can do this.
__gshared char[4] lookup = ['a', 't', 'g', 'c];

Be warned though these kinds of globals are not thread safe so 
mutation and accessing should be synchronized if your using more 
then one thread.









More information about the Digitalmars-d-learn mailing list