gpt4 book ai didi

ruby - 为什么 array.index 比 array.include 快?

转载 作者:数据小太阳 更新时间:2023-10-29 08:37:45 24 4
gpt4 key购买 nike

我正在处理一些大型数据集,并试图提高性能。我需要确定一个对象是否包含在数组中。我正在考虑使用 indexinclude?,所以我对两者都进行了基准测试。

require 'benchmark'

a = (1..1_000_000).to_a
num = 100_000
reps = 100

Benchmark.bmbm do |bm|
bm.report('include?') do
reps.times { a.include? num }
end
bm.report('index') do
reps.times { a.index num }
end
end

令我惊讶的是,index 要快得多。

               user     system      total        real
include? 0.330000 0.000000 0.330000 ( 0.334328)
index 0.040000 0.000000 0.040000 ( 0.039812)

由于 index 提供的信息比 include? 多,我原以为它会稍微慢一点,但事实并非如此。为什么更快?

(我知道 index 直接来自数组类,而 include? 是从 Enumerable 继承的。这可以解释吗?)

最佳答案

查看 Ruby MRI 源代码,似乎 index 使用优化的 rb_equal_optinclude? 使用 rb_equal。这可以在 rb_ary_includes 中看到和 rb_ary_index . Here是进行更改的提交。我不是很清楚为什么它用在 index 而不是 include?

您可能还会发现阅读关于此 feature 的讨论很有趣

关于ruby - 为什么 array.index 比 array.include 快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25779451/

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