pure-ifying my code

Jonathan M Davis jmdavisProg at gmx.com
Sun Nov 17 12:59:50 PST 2013


On Sunday, November 17, 2013 08:46:49 Ali Çehreli wrote:
> On 11/17/2013 02:55 AM, Jonathan M Davis wrote:
>  > And since additional calls to strongly pure functions are only
> 
> optimized out
> 
>  > within a single expression (or maybe statement - I'm not sure which - but
>  > certainly not across multiple statements), it's not like calls to
> 
> strongly
> 
>  > pure functions can be optimized out very often anyway.
> 
> I don't see why not.
> 
>      if (pure_func(a)) {
>          // ...
>      }
> 
>      // assume 'a' is not mutated here
> 
>      if (pure_func(a)) {
>          // ...
>      }
> 
> There is no reason why pure_func(a) cannot be executed only once, right?

The reason would be that the compiler doesn't do flow analysis and as I 
understand it, it makes zero attempt to optimize calls to pure functions 
outside of an expression. So,

auto foo = pure_func(a) * pure_func(a);

should result in only one call to pure_func, but something like

auto foo = pure_func(a);
auto bar = pure_func(a);

will definitely result in multiple calls to pure_func. It's not that it's 
impossible for the compiler to do it - it's perfectly possible. But doing so 
would require at least basic code flow analysis, and dmd almost never does any 
kind of code flow analysis.

So, a smarter compiler could optimize calls to strongly pure functions more 
than dmd does, but even then, I question that you'd get much optimized outside 
of example code, because I don't think that it's all that common for the same 
function to be called multiple times with the same arguments within a function 
- and you certainly can't save the result for use outside of a function, 
because that would mean compiler-generated memoization, which would would 
require storing the results of all of those function calls somewhere.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list