Wednesday, April 16, 2014

Python anti-pattern analysis

Range for iteration (1)

Python has a lot of internal optimization for operations for speed and readability. I have been advised that there is a "python anti-pattern" website, which greatly help to prevent me from using python "inappropriately". Here I did a little bit analysis over why these patterns are important in terms of speed.

1. Use range for iteration

    It is usually not necessary to use range(len(lista)) as a way to generate iteration over the list for indexing the list itself. Here is an example to show what is the difference.
Range for iteration (2)
    In "Range for iteration" figure, only changing "range" to "enumerate" does not improve the speed at all (even worse), however, switching the index searching ( a[i] ) does help to improve the speed a lot. This indicates that: if there is a need to access both index and list item itself, better to avoid index access. If one only need to access the value itself without a need for index, then the following example (2) would show what is the the best choice.
Range for iteration (3)

    The "anti-pattern" also suggest to use "zip" function, if there is a need to loop for two list, rather than using range(len()) statement. The test does not show an increase of speed, however, this "anti-pattern" rule may be made to read the code more readable.

2. Sentinel value in python

Usually, coming from a "C" background, I prefer to do a "check" for every condition statement: check whether a list has any element? using len(list); check if a variable is None, use "if a is None". However, this could be unnecessary in Python, as it has a rich sentinel value for the conditional variables. The following example shows how does the sentinel value improve the efficiency.


3. List comprehension
   
    There are so many rich intrinsic data structures in Python which has been optimized over and over ... it is better to save some looping time and directly utilize them. List comprehension is one of the most commonly used one. The example shown below indicates what is the speed gain.

    In general, there so many advanced skills ( or "tricks") to be used in Python. This is a powerful language, and I am excited to explore more along the way.

No comments:

Post a Comment