2021-10-28

Performance of temporary variables vs array element, which is faster, when?

Consider these examples using Python calling several functions returning a number, using an array element:

import numpy as np

my_array = np.zeros(looplength)

for j in range(0,looplength):

    temp = my_first_function(j)
    my_array[j] = temp
    a_1 = my_first_function(j,temp)
    a_2 = my_second_function(j,temp)
    a_3 = my_third_function(j,temp)
    ....
    a_N = my_Nth_function(j,temp)

vs

import numpy as np

my_array = np.zeros(looplength)

for j in range(0,looplength):

    my_array[j] = my_first_function(j)
    a_1 = my_first_function(j,my_array[j])
    a_2 = my_second_function(j,my_array[j])
    a_3 = my_third_function(j,my_array[j])
    ....
    a_N = my_Nth_function(j,my_array[j])

My question is: for performance, is it better to use a copy in a temporary variable or an access an array element directly, if this happens repeatedly? Also: how often does an array element need to be accessed for it to become faster to copy it?



from Recent Questions - Stack Overflow https://ift.tt/3mlg6Ww
https://ift.tt/eA8V8J

No comments:

Post a Comment