Search This Blog

Tuesday, May 27, 2014

Faster commands that improve performance

  • Tuple is faster than list
  • An operation like a_list = a_list + 1 is memory intensive


  1. Why is tuple faster than list?

    1. 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