Equivalent of Perl chomp?
tim.one at home.com
Sat Feb 2 06:09:15 CET 2002
> 1,000,000 iterations.
> Testing for length 1:
> Endswith 0.00000505
> sliceIt 0.00000209
> Testing for length 2:
> Endswith 0.00001137
> sliceIt 0.00001148
> Length 3:
> Endswith 0.00001055 [!]
> sliceIt 0.00001264
> Of course, these tests are with the tests succeeding. I'm
> presuming failure
> would shorten the timings, but I'm not going to bother checking that
> semi-believab-ly y'rs - steve
This is the kind of fun I was hoping the OP would have. Good job! A lesson
to take is that timing even seemingly trivial things can turn up major
surprises with seemingly trivial changes in exactly what it is you're
timing. The results are almost never accidental, but determining the true
causes can leave you crawling on your belly for weeks begging for relief.
A few things going on in this test under the covers:
+ endswith does indeed pay a large price for building a bound
method object every time. It's not only the dict lookup to
resolve "endswith", but also malloc and free to build the
bound method object and discard it afterwards.
+ The huge increase in sliceit's time going from 1 to 2 is due to
that s[:-1] creates a one-character string, and Python interns
those by magic: every instance of, e.g., 'a', no matter how
computed, is exactly the same object (that's not actually true,
but it's close <wink>). But 2-character computed strings are
not interned, so s[:-2] has to malloc a fresh string object each
time to hold the two characters, and free it later. endswith
doesn't have to build new string objects, so doesn't care as much.
Now for some real fun: I have no idea why endswith took a huge jump going
from 1 to 2. The saving grace for me is that it's so easy to find timing
mysteries that I'd go mad if I felt compelled to chase them all down, so I
can walk away without even looking back. I hope not everyone is so
well-adjusted <wink>, though, as I'd like to know why.
like-living-in-pumpkin-ly y'rs - tim
More information about the Python-list