[Zope-Coders] x.startswith() vs. x[ ..]

Tim Peters tim@zope.com
Sat, 1 Dec 2001 14:36:21 -0500


[Andreas Jung]
> I just made a small benchmark comparing  startwith()/endswith() on
> strings against the corresponding string slicing.  Using string methods
> is about 30% faster than slicing

Good point!  I expect the difference to be even greater for Unicode strings
(slicing requires building a new string object, and while building a regular
temp string object requires a malloc/free pair, a new Unicode string object
requires two such pairs).

> and sometimes the code is more readable.

Once you're used to {starts,ends}with() (about the third time you use them),
they're *always* more readable than slicing.  Also less error-prone:  while
it does happen, it's rare that people get the count wrong when slicing; the
more common screwup is spelling the slicing incorrectly, like trying
string[:-3] to get the last three chars instead of the correct string[-3:]
(or should that have been the other way around <wink>?).

> Maybe we should keep that in mind for performance reasons when working
> on Zope 2/3.

They're a rare pure win (better on all counts, worse on none).

turns-out-java-was-good-for-something-after-all<wink>-ly y'rs  - tim