简体   繁体   English

Python 2.7中获取字符串长度的性能

[英]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)? 当调用len("1234567890") ,性能是恒定的,即O(1),或者与字符串的长度成线性关系,即根据字符串的长度(在此示例中为字符串的长度)为O(n)是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. 使用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). 是O(1)。 The size of the string is stored in the object when it is created. 字符串的大小在创建时存储在对象中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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