Project

General

Profile

Actions

Feature #10227

closed

array.include? is much slower than array.index

Added by Darudmand (A N) over 10 years ago. Updated about 10 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

Updated by Glass_saga (Masaki Matsushita) about 10 years ago

  • Assignee set to Glass_saga (Masaki Matsushita)
  • Tracker changed from Bug to Feature
  • Status changed from Open to Assigned
Actions #2

Updated by Anonymous about 10 years ago

  • Status changed from Assigned to Closed
  • % Done changed from 0 to 100

Applied in changeset r47659.


Updated by Glass_saga (Masaki Matsushita) about 10 years ago

Result of benchmark script the same as ruby-core:64954.

Rehearsal --------------------------------------------
include?   0.100000   0.000000   0.100000 (  0.093951)
index      0.090000   0.000000   0.090000 (  0.092334)
----------------------------------- total: 0.190000sec

               user     system      total        real
include?   0.090000   0.000000   0.090000 (  0.081303)
index      0.080000   0.000000   0.080000 (  0.081296)
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0