Lin Ma
Lin Ma

Reputation: 10139

performance of get the length of a string in Python 2.7

When calling len("1234567890"), the performance is constant i.e. O(1), or linear to the length of the string, i.e. O(n) according to the length of the string (in this example, the length of the string is n=10)? If constant performance, why? And if linear performance, any ideas how to improve performance of getting the length of a string? Thanks.

Using Python 2.7.

regards, Lin

Upvotes: 0

Views: 2923

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177715

Check it:

C:\>py -m timeit -s "x='a'*1000" "len(x)"
10000000 loops, best of 3: 0.0959 usec per loop

C:\>py -m timeit -s "x='a'*10000" "len(x)"
10000000 loops, best of 3: 0.0902 usec per loop

C:\>py -m timeit -s "x='a'*100000" "len(x)"
10000000 loops, best of 3: 0.0927 usec per loop

It's O(1). The size of the string is stored in the object when it is created.

Upvotes: 4

Related Questions