Created
March 13, 2014 10:20
-
-
Save huacnlee/9525727 to your computer and use it in GitHub Desktop.
Ruby Array include? vs index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
user system total real | |
include? 30000 | |
18.460000 0.050000 18.510000 ( 18.587449) | |
index 30000 | |
2.940000 0.000000 2.940000 ( 2.947624) |
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)
什么情况, 为什么我这里 include? 和 index 相差不大.
我是 ruby 1.9.3
$ ruby -v
ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin13.0]
$ 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
include? 30000
30000
73.700000 0.040000 73.740000 ( 73.940654)
index 30000
58.830000 0.010000 58.840000 ( 59.140464)
好长时间啊,难道是我的电脑太次吗?