Reputation: 1845
What is the difference between these two approaches?
import time
start_time = time.time()
node_to_visit = [4]
print("My program took", time.time() - start_time, "to run")
start_time = time.time()
node_to_visit = []
node_to_visit.append(4)
print("My program took", time.time() - start_time, "to run")
Output:
My program took 7.43865966796875e-05 to run
My program took 0.00012230873107910156 to run
Upvotes: 0
Views: 162
Reputation: 23743
What is the difference between these two approaches?
>>> import dis
>>> def f():
... x = [4]
...
>>> def g():
... x = []
... x.append(4)
...
The first takes fewer bytecode operations than the second.
>>> dis.dis(f)
2 0 LOAD_CONST 1 (4)
2 BUILD_LIST 1
4 STORE_FAST 0 (x)
6 LOAD_CONST 0 (None)
8 RETURN_VALUE
>>> dis.dis(g)
2 0 BUILD_LIST 0
2 STORE_FAST 0 (x)
3 4 LOAD_FAST 0 (x)
6 LOAD_METHOD 0 (append)
8 LOAD_CONST 1 (4)
10 CALL_METHOD 1
12 POP_TOP
14 LOAD_CONST 0 (None)
16 RETURN_VALUE
>>>
>>> dis.dis(lambda : [4])
1 0 LOAD_CONST 1 (4)
2 BUILD_LIST 1
4 RETURN_VALUE
>>> dis.dis(lambda : [].append(4))
1 0 BUILD_LIST 0
2 LOAD_METHOD 0 (append)
4 LOAD_CONST 1 (4)
6 CALL_METHOD 1
8 RETURN_VALUE
Upvotes: 2
Reputation: 4670
I think the most obvious answer to the difference in time would be that example 1 takes 1 step to create a list [4]
while example 2 takes 2 steps to create the same list. Also, while I don't know how long it takes to initialize variables of different data types, I do know that variable initialization is (relatively) much shorter than function/method calls.
Upvotes: 1