Optimizing your Python Program: Code to watch out for
Change a list to a set
My all-time favorite easy optimization is replacing a list where I'm checking for duplicates with a set. The savings are enormous - in one instance taking a method's execution time from 650 seconds to 71 seconds - an order of magnitude! The key is, however, that your code is checking for duplicates in the list - like this:
if strIp not in myElems.ipAddrs:
myElems.ipAddrs.append(strIp)
To make this change, just change your list initialization from
myElems = []
## or
myElems = [initialElement]
to
myElems = set([])
## or
myElems = set([initialElement])
And change the way you add to the list - you don't need to check for duplicates any more:
myElems.ipAddrs.add(strIp)
Labels: python
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home