Skip to content

Instantly share code, notes, and snippets.

@potato2003
Last active June 19, 2019 14:10
Show Gist options
  • Save potato2003/bac11d2ec90ae87b5aad9aaa6517642e to your computer and use it in GitHub Desktop.
Save potato2003/bac11d2ec90ae87b5aad9aaa6517642e to your computer and use it in GitHub Desktop.
benchmark: split a string every n characters in Ruby
user system total real
String#scan 1.774321 0.007220 1.781541 ( 1.799350)
String.unpack 0.665138 0.003861 0.668999 ( 0.678201)
String#chars.each_slice.map(join) 10.444911 0.023717 10.468628 ( 10.521092)
String#[] slice with times iteration 2.244066 0.006614 2.250680 ( 2.264310)
String#slice with times iteration 2.271120 0.005431 2.276551 ( 2.290473)
require 'benchmark'
Benchmark.bm 40 do |r|
n = 100_000
str = ('a'..'z').to_a.join * 10
r.report "String#scan" do
n.times do
v = str.scan(/.{4}/)
end
end
r.report "String#unpack" do
n.times do
str.unpack("a4" * (str.size / 4))
end
end
r.report "String#chars.each_slice.map(join)" do
n.times do
v = str.chars.each_slice(4).map {|c| c.join "" }
end
end
r.report "String#[] slice with times iteration" do
n.times do
v = []
(str.length / 4).times do |i|
offset = i * 4
v << str[0+offset...4+offset]
end
end
end
r.report "String#slice with times iteration" do
n.times do
v = []
(str.length / 4).times do |i|
offset = i * 4
v << str.slice(0+offset...4+offset)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment