4

I would like to know how much the include? method can affect the performance if I have something like this:

array = [<array_values>]           # Read above for more information

(0..<n_iterations>).each { |value| # Read above for more information
  array.include?(value)
}

In cases <array_values> are 10, 100 and 1.000 and <n_iterations> are 10, 100, 1000.

7
  • 1
    Did you try running the code in IRB / Rails console? Commented Jun 25, 2011 at 3:45
  • Also, your question is a bit unclear to me. Can you provide an example of what array could be? Commented Jun 25, 2011 at 3:46
  • @Andrew Grimm - How can I try running the code in the IRB / Rails console and retrieve perfomance time or other important information about this matter? Commented Jun 25, 2011 at 3:46
  • @Ben Alpert - Array could be an array of string values. Commented Jun 25, 2011 at 3:47
  • 1
    Use benchmark Commented Jun 25, 2011 at 4:14

2 Answers 2

17

Use a Set (or equivalently a Hash) instead of an array, so that include is O(1) instead of O(n).

Or if you have multiple include to do, you can use array intersection & or subtraction - which will build a temporary Hash to do the operation efficiently.

Sign up to request clarification or add additional context in comments.

3 Comments

The asker now suggests that it is an array of strings, so conversion to a Set/Hash doesn't sound possible.
@Ben Alpert: Why not? An Array of <anything> can be converted to a Set of <anything>. If using a Hash, use the objects as the keys (and use true, say, for the corresponding values). Note that Set does exactly that internally.
Whoops, my bad. I misread the question as doing (essentially) array.each { |el| el.include? value }; you're completely right.
2

I think ruby-prof might be a good place to start. However, that performance data won't be useful without something else to compare this to. As in, "is the performance of this method better or worse than [some other method]?"

Also, note that as n_iterations increases larger than the size of array, this code will probably perform better, due to sheer number of #include? calls.

array.each do |value|
  (0..<n_iterations>).map.include?(value)
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.