简体   繁体   中英

performance of get the length of a string in Python 2.7

When calling len("1234567890") , the performance is constant ie O(1), or linear to the length of the string, ie 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM