-
-
Notifications
You must be signed in to change notification settings - Fork 30.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Optimize sum() for bools #80962
Comments
To count the number of items that satisfy certain condition you can use either sum(1 for x in data if pred(x)) or
where pred(x) is a boolean expression. The latter case is shorter but slower. There are two causes for this:
The first cause is out of the scope of this issue, but sum() can optimized for bools. $ ./python -m timeit -s "a = [True] * 10**6" -- "sum(a)"
Unpatched: 10 loops, best of 5: 22.3 msec per loop
Patched: 50 loops, best of 5: 6.26 msec per loop
$ ./python -m timeit -s "a = list(range(10**6))" -- "sum(x % 2 == 0 for x in a)"
Unpatched: 5 loops, best of 5: 89.8 msec per loop
Patched: 5 loops, best of 5: 67.5 msec per loop
$ ./python -m timeit -s "a = list(range(10**6))" -- "sum(1 for x in a if x % 2 == 0)"
5 loops, best of 5: 53.9 msec per loop |
I am not sure that this optimization should be added. sum(pred(x) for x in data) will be always slower than sum(1 for x in data if pred(x)) because more items is passed to sun() in the former case. It can be considered as an anti-pattern. |
Oh, I was going to withdraw this. |
Sorry, it seemed like a perfectly reasonable change when I was looking at the PR! |
I don't think anything _bad_ can happen with that optimization, if it's already written. And people (me included) do like to write shorter expressions instead of longer ones. |
Well, it is good for people who already sum bools. But if you are concerned about microoptimization, sum(1 for ... if ...) can be better variant. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: