我为基准测试运行了相同的测试。好像包括?比索引快,虽然不是很一致。
这是我针对两种不同场景的结果。
- ruby 代码和你的一样
user system total real
index 0.065803 0.000652 0.066455 ( 0.067181)
include? 0.065551 0.000590 0.066141 ( 0.066894)
- 另一个基准测试
user system total real
index 0.000034 0.000005 0.000039 ( 0.000037)
include? 0.000017 0.000001 0.000018 ( 0.000017)
代码:
require 'benchmark'
# parse ranks and return number of reports to using index
def solution_using_index(ranks)
return 0 if ranks.nil? || ranks.empty? || ranks.length <= 1
return ((ranks[0] - ranks[1] == 1) || (ranks[1] - ranks[0] == 1) ? 1 : 0) if ranks.length == 2
return 0 if ranks.max > 1000000000 || ranks.min < 0
grouped_ranks = ranks.group_by(&:itself)
report_to, rank_keys= 0, grouped_ranks.keys
rank_keys.each {|rank| report_to += grouped_ranks[rank].length if rank_keys.index(rank+1) }
report_to
end
# parse ranks and return number of reports to using include
def solution_using_include(ranks)
return 0 if ranks.nil? || ranks.empty? || ranks.length <= 1
return ((ranks[0] - ranks[1] == 1) || (ranks[1] - ranks[0] == 1) ? 1 : 0) if ranks.length == 2
return 0 if ranks.max > 1000000000 || ranks.min < 0
grouped_ranks = ranks.group_by(&:itself)
report_to, rank_keys= 0, grouped_ranks.keys
rank_keys.each {|rank| report_to += grouped_ranks[rank].length if rank_keys.include?(rank+1) }
report_to
end
test_data = [[3, 4, 3, 0, 2, 2, 3, 0, 0], [4, 4, 3, 3, 1, 0], [4, 2, 0] ]
Benchmark.bmbm do |bm|
bm.report('index') do
test_data.each do |ranks|
reports_to = solution_using_index(ranks)
end
end
bm.report('include?') do
test_data.each do |ranks|
reports_to = solution_using_include(ranks)
end
end
end