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>

<blockquote>
  <p>Is there any good reason for this? </p>
</blockquote>

<p>Having a special path for the empty set had not come up before.</p>

<blockquote>
  <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>
</blockquote>

<p>This is a reasonable optimization request.  I've made a <a href="http://bugs.python.org/file44565/set_diff_early_out.diff" rel="nofollow">patch</a> and will apply it shortly.  Here are the new timings with the patch applied:</p>

<pre><code> $ py -m timeit -s "r = range(10 ** 4); s = set()" "s.difference(r)"
10000000 loops, best of 3: 0.104 usec per loop
 $ py -m timeit -s "r = set(range(10 ** 4)); s = set()" "s.difference(r)"
10000000 loops, best of 3: 0.105 usec per loop
 $ py -m timeit -s "r = range(10 ** 4); s = set()" "s.difference_update(r)"
10000000 loops, best of 3: 0.0659 usec per loop
 $ py -m timeit -s "r = set(range(10 ** 4)); s = set()" "s.difference_update(r)"
10000000 loops, best of 3: 0.0684 usec per loop
</code></pre>

python performance set operators