Search code examples
language-agnosticcompiler-optimization

Using a variable to store a function call?


Let's say I had a pure function which takes a considerable amount of time to run. And in the main I wanted to call this function with the same arguments multiple times.

My ultimate question is, should I store the return value in a variable and use that or just call the function multiple times? Which way would take less computations?

Are compilers for modern languages (if any) able to tell whether a function is pure or not? If yes, are the compilers able to optimize away those multiple calls in the same block? If yes, then it makes more sense for me to just call those functions than to use placeholder variable (since I will be wasting computation doing the assignment/binding names)?

EDIT: here is an example

if myPureFunction(a,b) == 1:
    print(1)
elif myPureFunction(a,b) == 2:
    print(2)
elif myPureFunction(a,b) == 3:
    print(3)
else:
    print(4)

vs.

var = myPureFunction(a,b) 
if var == 1:
    print(1)
elif var == 2:
    print(2)
elif var == 3:
    print(3)
else:
    print(4)

Thanks in advance.


Solution

  • Your answer is depends from optimization of your compiler. If the body of function 'myPureFunction()' is in same translation unit (your C-file), then some compilers can perform optimization for first example and replace 3x calls of function to only one. But not all compilers can make this optimization and second variant will be better. I said it, because our compiler (that, i implemented in my work) can't do it =)