Not to beat a dead horse, but you can speed this up a bit more by making two changes that have become second nature to me now. The first is use map!
instead of map
to avoid creating a copy of the split array, and the second is to avoid use of the symbol to proc syntax (e.g. &:split
, which adds an extra operation that can be avoided with the more verbose syntax).
Benchmark follows:
require 'benchmark'
s = "one thing, two things, three things, four things"
result = ""
Benchmark.bmbm do |b|
b.report("strip/split (map/to_proc): ") { 1_000_000.times { result = s.split(",").map(&:strip) } }
b.report("strip/split (map): ") { 1_000_000.times { result = s.split(",").map { |e| e.strip } } }
b.report("strip/split (map!/to_proc): ") { 1_000_000.times { result = s.split(",").map!(&:strip) } }
b.report("strip/split (map!): ") { 1_000_000.times { result = s.split(",").map! { |e| e.strip } } }
b.report("regex: ") { 1_000_000.times { result = s.split(/\s*,\s*/) } }
end
Results:
user system total real
strip/split (map/to_proc): 5.230000 0.010000 5.240000 ( 5.283079)
strip/split (map): 4.660000 0.010000 4.670000 ( 4.716920)
strip/split (map!/to_proc): 4.440000 0.020000 4.460000 ( 4.492943)
strip/split (map!): 4.320000 0.010000 4.330000 ( 4.365386)
regex: 7.190000 0.060000 7.250000 ( 7.322932)
Remember to read the numbers relative to each other, not relative to the benchmarks provided in other answers.
"one thing, two things, three things, four things"
and{:things => things.to_s.tr("\n\t", "").strip.split(/,/)}
? Don't just copy exactly whatever you have. Make it into a question that people other than you can understand. Remove irrelevant things.