Why is string's startswith slower than in?

前端 未结 2 804
日久生厌
日久生厌 2020-12-24 10:35

Surprisingly, I find startswith is slower than in:

In [10]: s=\"ABCD\"*10

In [11]: %timeit s.startswith(\"XYZ\")
1000000 loops, be         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-24 11:03

    This is likely because str.startswith() does more than str.__contains__(), and also because I believe str.__contains__ operates fully in C, whereas str.startswith() has to interact with Python types. Its signature is str.startswith(prefix[, start[, end]]), where prefix can be a tuple of strings to try.

提交回复
热议问题