Created
March 22, 2013 06:29
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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