Slicing vs .startswith

Alex Martelli aleax at aleax.it
Mon Sep 22 18:52:12 EDT 2003


Paul wrote:

> However, what if you don't want case sensitivity?  For example, to
> check if a file is a jpg, I do name[-3:].lower() == 'jpg'.  This will
> work with both foo.jpg and foo.JPG.
> 
> Is this slower than name.lower().endswith('jpg')?  Is there a better
> solution altogether?

timeit.py gives me 0.9 microseconds for the less maintainable
name[:-3].lower()=='jpg' vs 1.7 for name.lower().endswith('jpg')
[and over 3 for re's].  Point is, _do I *care*_?  How many millions
of filenames will I check, when the extra overhead of checking
a million filenames in the more maintainable way is less than a
second?  How long will it have taken me to get those millions
of filenames into memory in the first place?

If this operation IS on the bottleneck, and a 0.8 microseconds
difference matters, I'll do the slicing -- but 99 times out of 100
I'll do the .endswith instead (I'll _start_ that way 100 times out
of 100, and optimize it iff profiling tells me that matters...).


Alex





More information about the Python-list mailing list