How good is startswith?

前端 未结 10 524
执笔经年
执笔经年 2021-01-07 19:38

Is

text.startswith(\'a\')  

better than

text[0]==\'a\'  

?

Knowing text is not empty and we a

10条回答
  •  梦谈多话
    2021-01-07 19:58

    I'd agree with the others that startswith is more readable, and you should use that. That said, if performance is a big issue for such a special case, benchmark it:

    $ python -m timeit -s 'text="foo"' 'text.startswith("a")'
    1000000 loops, best of 3: 0.537 usec per loop
    
    $ python -m timeit -s 'text="foo"' 'text[0]=="a"'
    1000000 loops, best of 3: 0.22 usec per loop
    

    So text[0] is amost 2.5 times as fast - but it's a pretty quick operation; you'd save ~0.3 microseconds per compare depending on the system. Unless you're doing millions of comparisons in a time critical situation though, I'd still go with the more readable startswith.

提交回复
热议问题