比.include更快的东西?

时间:2013-05-22 16:42:51

标签: ruby arrays include

我目前正在使用数组,我决定尝试使用.include替换和迭代搜索已排序的数组来加速我的一个函数?令我惊讶的是,该计划的总运行时间从2:12到9:53。我对此感到困惑,我去查看.include的源代码?事实证明它只是用C

编写的迭代检查
rb_ary_includes(VALUE ary, VALUE item)
{
        long i;

        for (i=0; i<RARRAY_LEN(ary); i++) {
                if (rb_equal(RARRAY_AREF(ary, i), item)) {
                        return Qtrue;
                }
        }
        return Qfalse;
}

有没有更快的方法来确定某个项目是否在排序数组中,可能是一个宝石?或者你需要用自己的二元搜索方法写一些东西吗?

1 个答案:

答案 0 :(得分:1)

我同意@mu,但是如果你真的想使用数组,并且正在使用Ruby 2.0.0,你可能想要查看bsearch方法。

arr = [1,2,3,5,6]
arr.bsearch { |x| 3 == x } # => 3
arr.bsearch { |x| 7 == x } # => nil

arr1 = ['1','2','3','4','5','6']
arr1.bsearch { |x| '2' == x } # => "2"
arr1.bsearch { |x| '7' == x } # => nil

http://www.ruby-doc.org/core-2.0/Array.html#method-i-bsearch

相关问题