As tuples are immutable their memory is pre-calculated during compile time. This makes accessing the tuple contents much faster than lists. Lists on the other hand to be efficient over allocate memory and hence the lookup is slightly slow.
I found this interesting command to test it:
[root@RHEL6 ~]# python -m timeit "x=(1,2,3,4,5,6,7,8)" 10000000 loops, best of 3: 0.0442 usec per loop [root@RHEL6 ~]# python -m timeit "x=[1,2,3,4,5,6,7,8]" 1000000 loops, best of 3: 0.249 usec per loop
Clearly tuples are much faster when it comes to accessing the elements
Why is tuple faster than list?
ReplyDeleteAs tuples are immutable their memory is pre-calculated during compile time. This makes accessing the tuple contents much faster than lists. Lists on the other hand to be efficient over allocate memory and hence the lookup is slightly slow.
DeleteI found this interesting command to test it:
[root@RHEL6 ~]# python -m timeit "x=(1,2,3,4,5,6,7,8)"
10000000 loops, best of 3: 0.0442 usec per loop
[root@RHEL6 ~]# python -m timeit "x=[1,2,3,4,5,6,7,8]"
1000000 loops, best of 3: 0.249 usec per loop
Clearly tuples are much faster when it comes to accessing the elements