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>IMO it's a matter of specialisation, consider:</p>

<pre><code>In [18]: r = range(10 ** 4)

In [19]: s = set(range(10 ** 4))

In [20]: %time set().difference(r)
CPU times: user 387 Âµs, sys: 0 ns, total: 387 Âµs
Wall time: 394 Âµs
Out[20]: set()

In [21]: %time set().difference(s)
CPU times: user 10 Âµs, sys: 8 Âµs, total: 18 Âµs
Wall time: 16.2 Âµs
Out[21]: set()
</code></pre>

<p>Apparently difference has specialised implementation for <code>set - set</code>.</p>

<p>Note that difference <em>operator</em> requires right hand argument to be a set, while difference allows any iterable.</p>

<p>Per @wim implementation is at <a href="https://github.com/python/cpython/blob/master/Objects/setobject.c#L1553-L1555" rel="nofollow">https://github.com/python/cpython/blob/master/Objects/setobject.c#L1553-L1555</a></p>

python performance set operators