Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <code>map!</code> instead of <code>map</code> to avoid creating a copy of the split array, and the second is to avoid use of the symbol to proc syntax (e.g. <code>&amp;:split</code>, which adds an extra operation that can be avoided with the more verbose syntax).</p> <p>Benchmark follows:</p> <pre><code>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(&amp;: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!(&amp;: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 </code></pre> <p>Results:</p> <pre><code> 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) </code></pre> <p><em>Remember to read the numbers relative to each other, not relative to the benchmarks provided in other answers.</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload