Project

General

Profile

Actions

Feature #10227

closed

array.include? is much slower than array.index

Added by Darudmand (A N) over 9 years ago. Updated over 9 years ago.

Status:
Closed
Target version:
[ruby-core:64954]

Description

I benchmarked both, and found that include? is about ten times slower than index (for the test below).

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

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

As per bug #8820, index has been optimised to use rb_equal_opt [1], whereas includes? uses rb_equal [2]. (Changelog here [3].)

[1] https://github.com/ruby/ruby/blob/c6da45b74cf9d420803c6ccbf4d527b1dfe4014e/array.c#L1462
[2] https://github.com/ruby/ruby/blob/c6da45b74cf9d420803c6ccbf4d527b1dfe4014e/array.c#L3851
[3] http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?revision=42704&view=revision

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0