我有一个处理大量ID的类.我需要它们在Initialize中,但只会在某些情况下使用它们.
将实例化具有600万个ID的数组的对象比实例化具有4个ID的数组的对象要慢吗?(在不使用此数据的情况下)
小智 5
无论你的阵列有多大.ruby中的变量是对象的引用.这意味着在两种情况下都会发送指针,但不会将实际数据作为参数发送.
require 'benchmark/ips'
class A
def initialize(arr)
@arr = arr
end
def mutate
@arr[0] = 11 # once this code been launched, it will change original object.
end
end
# Do not create test data in the bench!
big_one = 6_000_000.times.map { |_| rand(10)}
small_one = [1,2,3,4]
Benchmark.ips do |x|
x.report do
A.new(big_one)
end
x.report do
A.new(small_one)
end
x.compare!
end
Run Code Online (Sandbox Code Playgroud)
所以,结果:
Warming up --------------------------------------
125.218k i/100ms
128.972k i/100ms
Calculating -------------------------------------
3.422M (± 0.7%) i/s - 17.155M in 5.014048s
3.485M (± 0.5%) i/s - 17.540M in 5.033405s
Run Code Online (Sandbox Code Playgroud)
注意:你不能在基准测试中使用像#to_a这样的方法,(1..6_000_000)范围转换到数组是一个缓慢的操作,这会影响最终得分.