gpt4 book ai didi

ruby - 将大型数组传递给类时性能会降低吗?

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:45 25 4
gpt4 key购买 nike

我有一个处理大量 ID 的类。我需要它们处于初始化状态,但只会在某些情况下使用它们。

实例化一个包含 600 万个 ID 的数组的对象会比实例化一个包含 4 个 ID 的数组的对象慢吗? (在不使用该数据的场景下)

最佳答案

不管你的数组有多大。 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

所以,结果:

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

注意:不能在benchmark中使用#to_a之类的方法,(1..6_000_000)范围转换为数组是一个缓慢的操作,这会影响最终得分。

关于ruby - 将大型数组传递给类时性能会降低吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45871473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com