I wrote some script in Python that creates a giant 2D matrix (1000x1000 or bigger) and fills it with random numbers. And after that, it goes through every element of the matrix and changes the number to another one depending on the current element's neighbours (something like you do in Game Of Life).
And I noticed that if I write the same algorithm of checking the neighbours like
if neighbour on the left has the value of X:
do Al
Bl
and Cl
else:
do Dl
El
and Gl
now if neighbour on the right has the value of X:
do Ar
Br
and Cr
and so on...
this code runs much faster than a version using function calls:
def actionA(x):
do x
def actionB(x):
do x
def actionC(x):
do x
def check(n):
actionA(n)
actionB(n)
actionC(n)
for every neighbour:
check(neighbour)
I'm wondering why that is so. Is it because the script has to switch between the loop and functions when executing the function's code while it goes line-by-line when running the inlined code?