Boilerplate in rich comparison methods

Neil Cerutti horpner at yahoo.com
Sat Jan 13 17:05:53 EST 2007


On 2007-01-13, Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> wrote:
> On Sat, 13 Jan 2007 10:04:17 -0600, Paul McGuire wrote:
> [snip]
>
> Surely this is only worth doing if the comparison is expensive?
> Testing beats intuition, so let's find out...
>
> class Compare:
>     def __init__(self, x):
>         self.x = x
>     def __eq__(self, other):
>         return self.x == other.x
>
> class CompareWithIdentity:
>     def __init__(self, x):
>         self.x = x
>     def __eq__(self, other):
>         return self is other or self.x == other.x
>
> Here's the timing results without the identity test:
>
>>>> import timeit
>>>> x = Compare(1); y = Compare(1)
>>>> timeit.Timer("x = x", "from __main__ import x,y").repeat()
> [0.20771503448486328, 0.16396403312683105, 0.16507196426391602]
>>>> timeit.Timer("x = y", "from __main__ import x,y").repeat()
> [0.20918107032775879, 0.16187810897827148, 0.16351795196533203]
>
> And with the identity test:
>
>>>> x = CompareWithIdentity(1); y = CompareWithIdentity(1)
>>>> timeit.Timer("x = x", "from __main__ import x,y").repeat()
> [0.20761799812316895, 0.16907095909118652, 0.16420602798461914]
>>>> timeit.Timer("x = y", "from __main__ import x,y").repeat()
> [0.2090909481048584, 0.1968839168548584, 0.16479206085205078]
>
> Anyone want to argue that this is a worthwhile optimization? :)

Perhaps. But first test it with "==".

-- 
Neil Cerutti



More information about the Python-list mailing list