Why is a `for` loop so much faster to count True values?

后端 未结 5 1599
忘掉有多难
忘掉有多难 2020-12-08 13:20

I recently answered a question on a sister site which asked for a function that counts all even digits of a number. One of the other answers contained two functions (which t

5条回答
  •  囚心锁ツ
    2020-12-08 13:35

    @MarkusMeskanen's answer has the right bits – function calls are slow, and both genexprs and listcomps are basically function calls.

    Anyway, to be pragmatic:

    Using str.count(c) is faster, and this related answer of mine about strpbrk() in Python could make things faster still.

    def count_even_digits_spyr03_count(n):
        s = str(n)
        return sum(s.count(c) for c in "02468")
    
    
    def count_even_digits_spyr03_count_unrolled(n):
        s = str(n)
        return s.count("0") + s.count("2") + s.count("4") + s.count("6") + s.count("8")
    

    Results:

    string length: 502
    count_even_digits_spyr03_list 0.04157966522
    count_even_digits_spyr03_sum 0.05678154459
    count_even_digits_spyr03_for 0.036128606150000006
    count_even_digits_spyr03_count 0.010441866129999991
    count_even_digits_spyr03_count_unrolled 0.009662931009999999
    

提交回复
热议问题