Optimize Your Iterators
To a Ruby newcomer, Ruby iterators typically look like a convenient syntax for loops. In fact, iterators are such a good abstraction that even seasoned developers often forget that they really are nothing more than methods of Array and Hash classes with a block argument.
However, keeping this in mind is important for performance. We talked in Modify Arrays and Hashes in Place about the importance of in-place operations on hashes and arrays. But that’s not the end of the story.
Because a Ruby iterator is a function of an object (Array, Range, Hash, etc.), it has two characteristics that affect performance:
-
Ruby GC will not garbage collect the object you’re iterating before the iterator is finished. This means that ...
Get Ruby Performance Optimization now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.