If I write a C function that does something with an iterable then I create an Iterator first and then loop over it.
iterator = PyObject_GetIter(sequence);
if (iterator == NULL) {
return NULL;
}
while (( item = PyIter_Next(iterator) )) {
...
}
This works fine but I've also seen some functions using tp_iternext
:
iterator = PyObject_GetIter(sequence); // ....
iternext = *Py_TYPE(iterator)->tp_iternext;
while (( item = iternext(iterator) )) {
...
}
the second approach seems faster (I have only one data point: my Windows computer and my msvc compiler).
Is it just coincidence that the iternext
approach is faster and is there any significant difference between these two?
Links to the python documentation of both: PyIter_Next, tp_iternext I have read them but to me it's not clear when and why one should be preferred.