fastest way to detect a user type

Steven D'Aprano steve at pearwood.info
Sun Feb 1 04:32:58 EST 2009


Paul Rubin wrote:

> Steven D'Aprano <steve at pearwood.info> writes:
>> First question is, why do you care that it's slower? The difference
>> between the fastest and slowest functions is 1.16-0.33 = 0.83
>> microsecond.
> 
> That's a 71% speedup, pretty good if you ask me.

Don't you care that the code is demonstrably incorrect? The OP is
investigating options to use in Python 3, but the fastest method will fail,
because the "type is InstanceType" test will no longer work. (I believe the
fastest method, as given, is incorrect even in Python 2.x, as it will
accept ANY old-style class instead of just the relevant X or V classes.)

That reminds me of something that happened to my wife some years ago: she
was in a van with her band's roadies, and one asked the driver "Are you
sure you know where you're going?", to which the driver replied, "Who
cares? We're making great time." (True story.)

If you're going to accept incorrect code in order to save time, then I can
write even faster code:

def func4(ob):
    pass

Trying beating that for speed!


>> If you call the slowest function one million times, your code will
>> run less than a second longer.
> 
> What if you call it a billion times, or a trillion times, or a
> quadrillion times, you see where this is going?

It doesn't matter. The proportion of time saved will remain the same. If you
run it a trillion times, you'll save 12 minutes in a calculation that takes
278 hours to run. Big Effing Deal. Saving such trivial amounts of time is
not worth the cost of hard-to-read or incorrect code.

Of course, if you have profiled your code and discovered that *significant*
amounts of time are being used in type-testing, *then* such a
micro-optimization may be worth doing. But I already allowed for that:

"Does that really matter...?"
(the answer could be Yes)

"Unless you have profiled your code and this really is a bottleneck ..."
(it could be)


> If you're testing 
> 100-digit numbers, there are an awful lot of them before you run out.

Yes. So what? Once you've tested them, then what? If *all* you are doing
them is testing them, your application is pretty boring. Even a print
statement afterwards is going to take 1000 times longer than doing the
type-test. In any useful application, the amount of time used in
type-testing is almost surely going to be a small fraction of the total
runtime. A 71% speedup on 50% of the runtime is significant; but a 71%
speedup on 0.1% of the total execution time is not.



-- 
Steven




More information about the Python-list mailing list