Topic: Efficient looping?

I've got a situation where I need to loop through a fairly large dataset (250 or so) for matches on two criteria ie x =5 and y = 9. I have been doing this with .detect in a loop and I tried a manually constructed loop, both seem around the same speed. Is there any particularly efficient looping technique Ruby-wise?

I looked at deleting the each element after it was used (they only need to be accessed once) but it didn't seem to noticeably affect speed not could I find a particularly straightforward way of doing it. Ideas?

Re: Efficient looping?

I'm not familiar with the .detect method or with how intelligently ruby processes certain conditions. Could you post some example code?

From general programming experience, heres my 2 cents.

foreach (item k in someobject)
if(x != 5)
#at this point x must be = to 5
if (y == 3)
  ... do some stuff

That would mean that it wouldn't bother to check the value of y and go to the next item in the loop if x wasn't already = 5.

Re: Efficient looping?

I don't know if you will be able to get much better performance when dealing with Ruby only. However, check out Ruby Inline. It allows you to embed C code directly in your Ruby script. Great for optimizing little areas like this.

Railscasts - Free Ruby on Rails Screencasts

Re: Efficient looping?

After some thought I'm reworking the whole block to work through the big array rather than searching it, much more complicated for me to write but nowhere near as computationally expensive as looping over a 250 element array 250 times.