From: glass.saga@... Date: 2014-09-21T02:26:36+00:00 Subject: [ruby-core:65182] [ruby-trunk - Feature #10227] array.include? is much slower than array.index Issue #10227 has been updated by Masaki Matsushita. 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) ``` ---------------------------------------- Feature #10227: array.include? is much slower than array.index https://bugs.ruby-lang.org/issues/10227#change-49022 * Author: A N * Status: Closed * Priority: Normal * Assignee: Masaki Matsushita * Category: core * Target version: current: 2.2.0 ---------------------------------------- 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/