[EMAIL PROTECTED] wrote:
Steve Bethard wrote:
Robert Kern wrote:
  def square(x):
      return x*x
  map(square, range(1000))

versus
  [x*x for x in range(1000)]

Hint: function calls are expensive.

$ python -m timeit -s "def square(x): return x*x" "map(square, range(1000))" 1000 loops, best of 3: 693 usec per loop

$ python -m timeit -s "[x*x for x in range(1000)]"
10000000 loops, best of 3: 0.0505 usec per loop

Functions will often be complicated enought that inlining them is not feasible.

True, true. However, list comprehensions still seem to be comparable in speed (at least in Python 2.4):


$ python -m timeit -s "def f(x): return x*x" "[f(x) for x in xrange(1000)]"
1000 loops, best of 3: 686 usec per loop

$ python -m timeit -s "def f(x): return x*x" "map(f, xrange(1000))"
1000 loops, best of 3: 690 usec per loop

Presumably this is because the C code for the byte codes generated by a list comprehension isn't too far off of the C code in map. I looked at bltinmodule.c for a bit, but I'm not ambitious enough to try verify this hypothesis. ;)

Steve
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to