How good is startswith?

前端 未结 10 552
执笔经年
执笔经年 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:38

    def compo2():
        n = "abba"
        for i in range(1000000):
            n[:1]=="_"
    

    is faster than

    def compo():
        n = "abba"
        for i in range(1000000):
            n.startswith("_")
    

    cProfile reports 0.061 for compo2 compared to 0.954 for compo on my machine. This of interest in case you want to make a LOT of prefix checks for various "_mystring". If most strings don't start with underscores then using string[:1]== char before using startswith is an option to optimize your code. In a real application this method saved me about 15% of cpu time.

提交回复
热议问题