Skip to content

Instantly share code, notes, and snippets.

@huacnlee
Created March 13, 2014 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huacnlee/9525727 to your computer and use it in GitHub Desktop.
Save huacnlee/9525727 to your computer and use it in GitHub Desktop.
Ruby Array include? vs index
require 'benchmark'
total_times = 30000
items1 = []
items2 = []
items3 = []
Benchmark.bm do |x|
x.report("include?") {
total_times.times do |i|
items1 << i if !items1.include?(i)
end
puts " #{items1.size}"
}
x.report("index") {
total_times.times do |i|
items2 << i if items2.index(i) == nil
end
puts " #{items2.size}"
}
end
user system total real
include? 30000
18.460000 0.050000 18.510000 ( 18.587449)
index 30000
2.940000 0.000000 2.940000 ( 2.947624)
@datty258
Copy link

   user     system      total        real

include? 30000
30000
73.700000 0.040000 73.740000 ( 73.940654)
index 30000
58.830000 0.010000 58.840000 ( 59.140464)
好长时间啊,难道是我的电脑太次吗?

@tumayun
Copy link

tumayun commented Mar 14, 2014

   user     system      total        real

include? 30000
16.080000 0.000000 16.080000 ( 16.135302)
index 30000
15.940000 0.000000 15.940000 ( 15.953061)
=> [ 16.080000 0.000000 16.080000 ( 16.135302)
, 15.940000 0.000000 15.940000 ( 15.953061)

@tumayun
Copy link

tumayun commented Mar 14, 2014

什么情况, 为什么我这里 include? 和 index 相差不大.
我是 ruby 1.9.3

@huacnlee
Copy link
Author

$ ruby -v
ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin13.0]

@huacnlee
Copy link
Author

$ ruby -v
ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-linux]

$ ruby test.rb
user system total real
include? 30000
21.650000 0.000000 21.650000 ( 21.662378)
index 30000
3.930000 0.000000 3.930000 ( 3.931389)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment