Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>just <code>timeit()</code>:</p> <pre><code>In : a = (3, 2, 9, 4) In : f1 = lambda: [x + 1 for x in a] In : f2 = lambda: tuple(x + 1 for x in a) In : timeit.timeit(f1) Out: 0.595026969909668 In : timeit.timeit(f2) Out: 2.360887050628662 </code></pre> <p>so it seems that the tuple constructor variant takes about four times as long, I guess because list comprehensions are fairly optimized (in cpython).</p> <p>But let's take a closer look:</p> <pre><code>In : f3 = lambda: list(x + 1 for x in a) In : timeit.timeit(f3) Out: 2.5421998500823975 </code></pre> <p>so this takes about the same time as the tuple construction, which indicates that the performance penalty lies in the generator expression overhead. (we can rule out list / tuple construction, see edit below)</p> <p>It is even about twice as slow as to <code>map()</code> the list:</p> <pre><code>In : inc = partial(operator.add,1) In : f4 = lambda:map(inc, a) In : timeit.timeit(f4) Out: 1.2346529960632324 </code></pre> <p>I think this really boils down to (cpython) implementation details, so don't rely on this. Anyway - don't worry about performance, it's just a factor of 2-4, use the method which is best to read.</p> <p>If you really hit performance bottlenecks, investigate and optimize them <em>after</em> you noticed them. And I bet a factor 4 in a list manipulation will be the least of your problems, then.</p> <p><strong>Edit:</strong> Someone mentioned that the lookup cost of "tuple" could cause the slowdown, but this is not the case:</p> <pre><code>In : f5 = lambda: tuple([x + 1 for x in a]) In : timeit.timeit(f5) Out: 0.7900090217590332 </code></pre> <p>So I guess it really is the generator expressions overhead which slows things down.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload