Skip to content

Instantly share code, notes, and snippets.

@dbenhur
Created March 22, 2013 06:29
Show Gist options
  • Save dbenhur/5219395 to your computer and use it in GitHub Desktop.
Save dbenhur/5219395 to your computer and use it in GitHub Desktop.
Benchmark for approaches to SO [Split a string into parts in efficient way](http://stackoverflow.com/questions/15563251/split-a-string-into-parts-in-efficient-way/15563862)
#!/usr/bin/env ruby
require 'benchmark'
# 456976 four character words
STR = ('aaaa'..'zzzz').to_a * ' '
N = 10
puts RUBY_DESCRIPTION
puts "#{N} times on string of size #{STR.size}"
def original
arr = STR.split(" ")
set_element = arr.each_cons(2).to_a
sub_str = set_element.map {|i| i.join(' ')}
end
def sergio
arr = STR.split(" ")
sub_str = arr.each_with_object([]).with_index do |(el, memo), idx|
if idx % 2 == 0
memo << el
else
memo.last << ' ' << el
end
end
end
def dbenhur
STR.scan(/\S+(?:\s+\S+)?/)
end
Benchmark.bm(10) do |x|
[:original, :sergio, :dbenhur].each do |method|
x.report(method.to_s) { N.times { send(method) } }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment