Why does Python's set difference method take time with an empty set?
<p>Here is what I mean:</p>

<pre><code>&gt; python -m timeit "set().difference(xrange(0,10))"   
1000000 loops, best of 3: 0.624 usec per loop

&gt; python -m timeit "set().difference(xrange(0,10**4))"
10000 loops, best of 3: 170 usec per loop
</code></pre>

<p>Apparently python iterates through the whole argument, even if the result is known to be the empty set beforehand. Is there any good reason for this? The code was run in python 2.7.6.</p>

<p>(Even for nonempty sets, if you find that you've removed all of the first set's elements midway through the iteration, it makes sense to stop right away.)</p>

<p>When Python core developers add new features, the first priority is correct code with thorough test coverage.  That is hard enough in itself.  Speedups often come later as someone has the idea and inclination.  I opened a tracker issue <a href="https://bugs.python.org/issue28071" rel="nofollow">28071</a> summarizing the proposal and counter-reasons discussed here.  I will try to summarize its disposition here.</p>

<p>UPDATE: An early-out for sets that start empty has been added for 3.6.0b1, due in about a day.</p>

python performance set operators