Tuesday, February 5, 2008

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:

Sunday, February 3, 2008

Deep Thoughts

  1. Coca-cola is like a Krispy-Kreme doughnut: The first taste is heavenly ambrosia, the rest merely "just ok."
  2. Lavender-scented natural deodorant from a health-food store will leave you smelling less like lavender and more like au natural.
  3. Can you make it through "Cloverfield" without puking? Can you ride the Disney teacups for 2 hours straight without puking? The answers to these questions are always the same.

Labels: