Joohwan
Joohwan

Reputation: 2512

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.

Upvotes: 0

Views: 93

Answers (2)

Egg Head
Egg Head

Reputation: 379

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 =)

Upvotes: 1

Gavin Perkins
Gavin Perkins

Reputation: 693

I think the answer you may be looking for is recursion. It means to call the same function multiple times, however it breaks the problem down with each function call.(But I honestly don't completely understand what your actual question is)

Here is a simple recursion example from TheNewBoston that may help you.

https://www.youtube.com/watch?v=fpuWkZs51aM

Upvotes: -1

Related Questions