I am using Ruby on Rails 3.0.7 and I would like to iterate over an array of objects (class istances) except for the element with id equal to 1 (the id refers to the array[1] index).
I know that I can use an if statement “internally” to an each statement and doing that I check for each “current”\”considered” element if id == 1. However, since the array is populated of a lot of data, I would like to find another way in order to accomplish the same things in a more performant way (avoiding to run the if each time).
How can I do?
Is IMHO a better way of doing the selection instead of using your own explicit
ifstatement. I believe, however, that it will result in approximately the same performance as usingif, maybe even slightly lower.If after benchmarking as others have suggested you know that the time this takes is definitely slower than what you can allow it, and it is the selection causing the slowness then this can be easily modified to remove the selection in a number of ways:
Unfortunately I believe this will also be slower than running the simple if. One that I believe might have the potential for speed is:
But this again has a high possibility of being slower.
EDIT
Benchmark is in this gist. These results actually surprised me, reject is by far the slowest option, followed by the ranges. The highest performing after not removing the element at all was using
firstanddropto select all the elements around it.The results as a percentage using no selection as a baseline:
Obviously this is highly dependant on what you do with the elements, this was testing with probably the fastest operation Ruby can perform. The slower the operation the less difference these will have. As always: Benchmark, Benchmark, Benchmark