Python: List and Tuple performance benchmark
Suppose you have two options to implement a solution using a programming language, what are important factors to select one of options? I do believe one of concerns for a programmer would be performance benchmark between those options.
In this short blog post I’d like to share my simple code and results for performance benchmark between Python
tuple. Two features to create a list, but with this difference, that
tuples are immutable and you can’t alter them after initializing.
Following code shows a simple usage of
tuple to create a series of items:
# this is a list, you can alter it in next lines l = [1, 2, 3, 4, 5] # this is a tuple and it's immutable t = (1, 2, 3, 4, 5)
Please note that you can store different data types as an item for both
My scenario to make a performance benchmark between
tuple is retrieving 2,000,000 random items from a
tuple) with 1,000,000 items.
Here is the source code for
import time from random import randint x = 1000000 demo_list =  # add items to list while x > 0: demo_list.append(x) x = x - 1 start = time.clock() # find random items from list y = 2000000 while y > 0: item = demo_list[randint(0, 999999)] y = y - 1 # print the elapsed time print (time.clock() - start)
Following chart illustrates the performance benchmark between
tuple on a Mac OS X 10.9.3 and Python 2.7.5:
- Tuple: 5.1217s
- List: 5.2462s
And it seems
tuples are a little bit faster in retrieving items.
You can download the source code for both
tuple from my Github account:
Source: New feed