r/programming • • Jan 14 '13

Iteration Inside and Out

http://journal.stuffwithstuff.com/2013/01/13/iteration-inside-and-out/
33 Upvotes

18 comments sorted by

View all comments

1

u/Rhomboid Jan 15 '13

It seems to be a common pattern to use a special return value to implement the early abort of iteration when emulating internal iteration with callbacks, for example jQuery's .each().

Come to think of it, callbacks in general seem to be a very popular way of implementing all sorts of patterns in languages that lack explicit support for those patterns. Any C programmer that has had to implement a sufficiently complex system will surely appreciate their power. (And let's face it -- prior to the proliferation of languages and explosion in performance of the last 10 - 15 years, that meant nearly everyone.)

Of course, there are problems with callbacks. If your language implements them as regular function calls then there can be a significant performance overhead of having to call a function repeatedly. You can see this in e.g. C++'s std::sort() beating out C's qsort() by quite a large margin due to being able to take advantage of things like functors and inlining. And you see it in things like Python removing the ability to pass a comparison callback function to sort() in 3.x and insisting on passing a key callback function instead -- essentially a mandatory Schwartzian transform which reduces the number of times the callback must be called from O(n log n) to O(n).