使用Ruby'include?'的性能 方法

use*_*052 1 ruby arrays hash performance

我想知道include?如果我有这样的东西,该方法会对性能产生多大影响:

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

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

<array_values>10,100和1.000的情况下,是10,100,1000 <n_iterations>.

Mar*_*une 12

使用Set(或等效的a Hash)而不是数组,这样就include可以O(1)代替O(n).

或者如果你有多个include要做,你可以使用数组交集&或减法-,这将构建一个临时Hash的高效操作.

  • @Ben Alpert:为什么不呢?*<anything>*的数组可以转换为一组*<anything>*.如果使用Hash,则使用对象作为键(并使用`true`,例如,对应的值).请注意,`Set`在内部完全相同. (4认同)