为什么array.index比array.include快? [英] Why is array.index faster than array.include?

查看:147
本文介绍了为什么array.index比array.include快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与一些大型数据集,并试图以提高性能。我需要来确定对象是否包含在数组中。我用的是既考虑首页包括哪些内容?,所以我既为基准

 要求'标杆'A =(1..1_000_000).to_a
NUM = 100_000
代表=​​ 100Benchmark.bmbm做| BM |
  bm.report(包括哪些内容?)做
    reps.times {a.include? NUM}
  结束
  bm.report(索引)做
    reps.times {a.index NUM}
  结束
结束

令人惊讶的(对我来说),首页是相当快的。

 用户系统的总实际
包括? 0.330000 0.000000 0.330000(0.334328)
指数0.040000 0.000000 0.040000(0.039812)

由于首页提供了比详细信息包括哪些内容?,我本来期望它,如果任何事都要稍微慢一些,虽然这并非如此。为什么快?

(我知道,首页直接从数组类来临,包括哪些内容?是可枚举​​继承。可能解释吗?)


解决方案

纵观红宝石MRI源,似乎首页使用了优化的 rb_equal_opt ,而包括哪些内容?使用 rb_equal 。这可以在 rb_ary_includes 并的 rb_ary_index 这里是提交,使得该更改。它不是立即清楚,我为什么它在指数使用,而不是包括哪些内容?

您也可能会发现有趣的阅读这篇功能

I'm working with some large datasets, and trying to improve performance. I need to determine whether an object is contained in an array. I was considering using either index or include?, so I benchmarked both.

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

Surprisingly (to me), index was considerably faster.

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

Since index provides more information than include?, I would have expected it to be slightly slower if anything, although this was not the case. Why is it faster?

(I know that index comes directly from the array class, and include? is inherited from Enumerable. Might that explain it?)

解决方案

Looking at the Ruby MRI source, it seems that index uses the optimized rb_equal_opt while include? uses rb_equal. This can be seen in rb_ary_includes and rb_ary_index. Here is the commit that made the change. Its not immediately clear to me why its used in index and not include?

You might also find it interesting to read the discussion of this feature

这篇关于为什么array.index比array.include快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆