1

Hmm..can't yet read this yet..but does Ruby Array#assoc use linear search?

rb_ary_assoc(VALUE ary, VALUE key)
{
    long i;
    VALUE v;

    for (i = 0; i < RARRAY_LEN(ary); ++i) {
        v = rb_check_array_type(RARRAY_PTR(ary)[i]);
        if (!NIL_P(v) && RARRAY_LEN(v) > 0 &&
            rb_equal(RARRAY_PTR(v)[0], key))
            return v;
    }
    return Qnil;
}
ovatsug25
  • 7,786
  • 7
  • 34
  • 48

2 Answers2

5

Personally, I find the Rubinius source code much easier to read than the YARV source code. (Actually, I find all other Ruby implementations' source code easier to read than YARV or MRI.)

This is the implementation of Array#assoc from Rubinius:

def assoc(obj)
  each do |x|
    if x.kind_of? Array and x.first == obj
      return x
    end
  end

  nil
end

So, yes it is easy to see that it indeed does use a linear search.

But you don't really need to look at the source code to figure that out. What else could it be? There is no structure or order that could be exploited to speed it up, unlike with a search tree or a sorted array.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
4

Yes; it's iterating over the array: RARRAY_PTR(ary)[i]

Which is the only thing that makes sense, given an array may or may not be sorted.

(Noting that Ruby 2 will introduce a bsearch, and there are at least 2-3 gems for binary searches, if you are concerned with speed. See https://stackoverflow.com/a/8672512/438992 for details.)

Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 1
    With the caveat that a binary search requires the array be presorted, which has its own cost associated with it. Hmm. At the introduction of `bsearch`, will we also see a SortedArray type? – the Tin Man Jan 23 '13 at 16:10