Commit 488512b
authored
A (very) slight speed improvement for iterating over bytes (#21705)
My mentee @xvxvxvxvxv noticed that iterating over array.array is
slightly faster than iterating over bytes. Looking at the source I
observed that arrayiter_next() calls `getitem(ao, it->index++)` wheras
striter_next() uses the idiom (paraphrased)
item = PyLong_FromLong(seq->ob_sval[it->it_index]);
if (item != NULL)
++it->it_next;
return item;
I'm not 100% sure but I think that the second version has fewer
opportunity for the CPU to overlap the `index++` operation with the
rest of the code (which in both cases involves a call). So here I am
optimistically incrementing the index -- if the PyLong_FromLong() call
fails, this will leave the iterator pointing at the next byte, but
honestly I doubt that anyone would seriously consider resuming use of
the iterator after that kind of failure (it would have to be a
MemoryError). And the author of arrayiter_next() made the same
consideration (or never ever gave it a thought :-).
With this, a loop like
for _ in b: pass
is now slightly *faster* than the same thing over an equivalent array,
rather than slightly *slower* (in both cases a few percent).1 parent c36dbac commit 488512b
1 file changed
+2
-6
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
3139 | 3139 | | |
3140 | 3140 | | |
3141 | 3141 | | |
3142 | | - | |
3143 | 3142 | | |
3144 | 3143 | | |
3145 | 3144 | | |
| |||
3148 | 3147 | | |
3149 | 3148 | | |
3150 | 3149 | | |
3151 | | - | |
3152 | | - | |
3153 | | - | |
3154 | | - | |
3155 | | - | |
| 3150 | + | |
| 3151 | + | |
3156 | 3152 | | |
3157 | 3153 | | |
3158 | 3154 | | |
| |||
0 commit comments