From: bugfs_ruby-lang@... Date: 2014-09-11T06:31:54+00:00 Subject: [ruby-core:64954] [ruby-trunk - Bug #10227] [Open] array.include? is much slower than array.index Issue #10227 has been reported by A N. ---------------------------------------- Bug #10227: array.include? is much slower than array.index https://bugs.ruby-lang.org/issues/10227 * Author: A N * Status: Open * Priority: Normal * Assignee: * Category: core * Target version: current: 2.2.0 * ruby -v: ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux] * Backport: 2.0.0: UNKNOWN, 2.1: UNKNOWN ---------------------------------------- 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 -- https://bugs.ruby-lang.org/