这是基准
require 'benchmark'
# create random array
arr = 40000.times.map { rand(100000).to_s }
r1 = ''
r2 = ''
r3 = ''
Benchmark.bm do |x|
x.report {
r1 = (arr.map { |s|
"[#{s}]"
}).join
}
x.report {
r2 = arr.inject('') { |memo, s|
memo + "[#{s}]"
}
}
x.report {
r3 = ''
arr.each { |s|
r3 << "[#{s}]"
}
}
end
# confirm result is same
puts r1 == r2
puts r2 == r3
这是结果
user system total real
0.047000 0.000000 0.047000 ( 0.046875)
5.031000 0.844000 5.875000 ( 5.875000)
0.031000 0.000000 0.031000 ( 0.031250)
true
true
有什么方法可以让inject
速度更快吗?