len() calls to python strings

I’m pretty confused about the results I’m getting from a little python test involving len() on strings. Since strings are immutable, I was wondering what happens when len() is called, and what performance considerations I may need to keep in mind. I figure if it was immutable, calls to len() might get cached, and there may be very little performance impact. However, what I found was that over 1 million iterations, twice as many len() calls on a string is roughly 3 times slower than an iteration with only one call. When I called the string’s __len__() method instead, the two are much more comparable, and the one with a single call actually took more time than when calling len(). Weird. Can anyone further enlighten me? Perhaps my testing method is bad (I know it’s not a very good test… I’m just doing it because I can’t sleep at the moment.)

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*