By how much assignment is slower/faster than indexation?

73 Views Asked by At

When does redeclaring a new variable faster than accessing an item in a list repeatedly in python?

for example with this list -

import time

fruits = ["orange", "banana", "strawberry", "apple"]

when running this code

timesToRun = 1000000
timesToAccess = 100

start_time = time.time()
for x in range(timesToRun):
    for y in range(timesToAccess):
        tempFruit = fruits[2] # Accessing the list directly
print("--- %s seconds ---" % (time.time() - start_time))


start_time = time.time()
for x in range(timesToRun):
    myFruit = fruits[2] # Declaring a new variable
    for y in range(timesToAccess):
        tempFruit = myFruit # Accessing the variable
print("--- %s seconds ---" % (time.time() - start_time))

And I got the following print -

--- 5.268802165985107 seconds ---
--- 4.507154226303101 seconds ---

so clearly redeclaring the item is faster than accessing it 100 times,

but when I am only accessing the item once

timesToRun = 10000000
timesToAccess = 1

the print is

--- 1.948554277420044 seconds ---
--- 2.1312568187713623 seconds ---

so now it is faster to just access it directly.

So my question is what is the threshold, when is it better to redeclare the item than access it directly? and with a dictionary or NumPy arrays is it any different answer?

EDIT: I guess my question can also be by how much does declaring a new variable is slower then just accessing a list.

0

There are 0 best solutions below