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.)

Advertisements

One Comment

  1. Posted April 2, 2013 at 9:52 am | Permalink

    I am extremely inspired together with your writing abilities as well as
    with the layout on your blog. Is that this a paid subject or
    did you customize it yourself? Either way keep up the excellent quality writing, it is rare to peer a nice
    blog like this one these days..


Post a Comment

Required fields are marked *
*
*

%d bloggers like this: