Reputation: 103
I have a function that performs a number of computations on an array variable. The code will be running on a cheap low performance single board computer (like the Raspberry Pi, I do not know the exact board at this time). This function is a major function of the overall program. I require the program to run fast even with heavy data present in the array variable. I am worried about the memory management and overall speed of the program. I am thinking of two ways for this.
Question: Should I use different intermediate variables, or should I use the same variable for the different computations. Which of the two below methods would be efficient in terms of memory management and processing-speed? Is there a better way than the below?
Option 1:
def function_1(a):
#some code
b = computation_1(a)
#some code
c = computation_2(b)
#some code
d = computation_3(c)
#some code
return d
Option 2:
def function_2(a):
#some code
a = computation_1(a)
#some code
a = computation_2(a)
#some code
a = computation_3(a)
#some code
return a
Note: I know of this coding style:
computation_2(computation_1(a))
...
However due to the different nature of the various functions, I need to do some preprocessing before sending to them, represented by the "#some code"
Upvotes: 0
Views: 98
Reputation: 8212
Normally, the CPU time difference will be negligible.
However, Option 1 creates b and c, and only when it returns will b and c be available for garbage collection. Option 2 doesn't keep intermediate results hanging around for so long. If the intermediates are small, this is also irrelevant. But if they are objects occupying tens or hundreds of megabytes (on a Pi with only 512Mb or 1Gb of RAM), this could make the difference between a program which swaps or crashes for lack of RAM, and a program which does not.
So use Option 2, provided the intermediates are of no use the moment the next step is complete.
Upvotes: 1
Reputation: 21285
The difference would be negligible. The overhead of registering a new variable and assigning it to the result is too small to be noticed.
Upvotes: 1