Fully transitive const is not necessary

Jason House jason.james.house at gmail.com
Thu Apr 3 06:48:13 PDT 2008


Koroskin Denis Wrote:

> It works, you are very glad that your program is parallelized and uses  
> full power of your multi-processor CPU.
> But now you want to make some optimizations to speed it up a little. You  
> add some SSE instruction in assembly (it's ok in pure methods, I hope?).
> And then you take a step further and it looks like you calculate  
> determinant for your Matrix every time, and it consumes quite some time.  
> You move you determinant calculations to class' ctor and just store the  
> value. But now it turns out that performance degraded dramatically because  
> now you are forced to calculate determinant for every Matrix, even  
> temporary ones, during addition, subtruction etc.
> 
> A C++ programmer would add mutable member here:
> 
> This is *transparent* optimization, and it's a programmer now who makes  
> guaranties, that his code makes no side effect. Yes, binary represination  
> of the class is changed, but its logical invariance is preserved. If  
> programmers fails to do it correctly, then it's his fault. By signing his  
> code as pure he claims that the method is thread-safe, doesn't rely on  
> other threads' execution order, calls to it can be rearranged and given  
> the same input it yields the same result.
> 
> You might say that this code smells, but it's correct. And it could look  
> slightly better if mutable was not a user-defined template hack, but a  
> language-level feature. You just should expose some restrictions on its  
> usage (like, only private members can be mutable, access to it can be  
> achieved via read-write lock only  
> http://en.wikipedia.org/wiki/Readers-writers_problem).
> 
> IMO, mutable is a powerful optimization mechanish, that should be used  
> with *great* care.

I think the future of D will no require the mutable keyword as you describe.

class matrix{
  pure int determinant(){ ... }
  ...
}

By simply making the determinant function pure, the compiler is free to do optimization/caching of the result.  I haven't been in the habit of giving compilers that much trust...



More information about the Digitalmars-d mailing list