0

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

asked Jun 16, 2016 at 1:34
2

1 Answer 1

4

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.

answered Jun 16, 2016 at 1:38

3 Comments

This reminds me of assembly where you had to store the length of strings for uses such as printing to stdout.
@MoonCheesez, it's all convention. I could write assembly that uses nul-terminated strings instead, but it would be O(n) instead for getting length.
Thanks Mark, excellent reply, vote up and mark your reply as answer.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.