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| # Rea开发者_Python百科d above for more information
array.include?(value)
}
In cases <array_values>
are 10, 100 and 1.000 and <n_iterations>
are 10, 100, 1000.
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.
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
精彩评论