[PATCH 5 of 7] revset: introduce a filterrevs function

Matt Mackall mpm at selenic.com
Sat Jun 23 11:42:19 CDT 2012


On Fri, 2012-06-22 at 20:35 -0500, Augie Fackler wrote:
> On Jun 22, 2012, at 4:45 PM, Pierre-Yves David wrote:
> 
> >> +    except (AttributeError, TypeError, KeyError):
> >> +        pass
> >> +    return filter(subset.__contains__, revs)
> > 
> > You seems to like the try:..except: pattern for common code path. It's look like a bad idea. I do not know how awful the code is with standard if but having such a wide silent except "AttributeError", "TypeError", and "KeyError" seems a perfect way to loose hours in debugging later.
> > 
> > Moreover the code path is very implicit and then hard to follow
> 
> Very often this performs significantly better than the alternatives, especially in cases where the exception-based codepath is actually exceptional.

Baseline:

$ python -m timeit -s 'a = {1:2}' -c "a[1]"
10000000 loops, best of 3: 0.033 usec per loop

Naive:

$ python -m timeit -s 'a = {1:2}' -c "a.get(1)"
10000000 loops, best of 3: 0.08 usec per loop
$ python -m timeit -s 'a = {1:2}' -c "a.get(2)"
10000000 loops, best of 3: 0.079 usec per loop

Look before you leap (what most of Mercurial uses):

$ python -m timeit -s 'a = {1:2}' -c "if 1 in a: a[1]"
10000000 loops, best of 3: 0.054 usec per loop
$ python -m timeit -s 'a = {1:2}' -c "if 2 in a: a[2]"
10000000 loops, best of 3: 0.027 usec per loop

The try/except approach:

$ python -m timeit -s 'a = {1:2}' -c "try: a[1]
except: pass"
10000000 loops, best of 3: 0.04 usec per loop
$ python -m timeit -s 'a = {1:2}' -c "try: a[2]
except: pass"
1000000 loops, best of 3: 0.4 usec per loop

As you can see, the try/except approach is an order of magnitude slower
on a miss, while the look before you leap approach actually gets faster.
Using the above numbers[1], if your hit percentage is less than about
_96%_, try/except loses.

This is why most of the caches in hg are written like this:

 if x not in cache:
   cache[x] = lookup(x)
 return cache[x]

Also, it's prettier.

[1] breakeven at (b2 - b1) / (g1 + b2 - g2 - b1)
-- 
Mathematics is the supreme nostalgia of our time.




More information about the Mercurial-devel mailing list