Skip to content

Instantly share code, notes, and snippets.

@agibralter
Last active December 12, 2015 08:29
Show Gist options
  • Save agibralter/4744055 to your computer and use it in GitHub Desktop.
Save agibralter/4744055 to your computer and use it in GitHub Desktop.
split vs. index
require 'benchmark'
n = 100000
a = nil
b = nil
c = nil
STRING = "foo=bar; domain=example.com; path=/; expires=Sat, 09-Feb-2013 07:27:33 GMT; HttpOnly".freeze
Benchmark.bm do |x|
x.report do
n.times do
a = STRING.split(/\s*;\s*/).first
end
end
x.report do
n.times do
b = STRING.split(';').first
end
end
x.report do
n.times do
i = STRING.index(';')
c = STRING[0...i]
end
end
end
puts a
puts b
puts c
# user system total real
# 0.810000 0.010000 0.820000 ( 0.805447)
# 0.200000 0.000000 0.200000 ( 0.207243)
# 0.100000 0.000000 0.100000 ( 0.098045)
# foo=bar
# foo=bar
# foo=bar
require 'benchmark'
n = 100000
a = nil
b = nil
c = nil
d = nil
STRING = "foofoofoofoofoofoo=barbarbarbarbarbar; bazbazbazbazbazbaz=quxquxquxquxquxqux; foofoofoofoofoofoo=barbarbarbarbarbar".freeze
Benchmark.bm do |x|
x.report do
n.times do
a = STRING.split(/\s*;\s*/)
end
end
x.report do
n.times do
b = STRING.split('; ')
end
end
x.report do
n.times do
c = STRING.split(';').map { |s| s.strip }
end
end
x.report do
n.times do
str = STRING.dup
res = []
while true
if i = str.index(';')
res << str[0...i].strip
str = str[i+1..-1]
else
res << str.strip
break
end
end
d = res
end
end
end
puts a.inspect
puts b.inspect
puts c.inspect
puts d.inspect
#        user     system      total        real
#    0.730000   0.010000   0.740000 (  0.729943)
#    0.140000   0.000000   0.140000 (  0.141725)
#    0.350000   0.000000   0.350000 (  0.349824)
#    0.640000   0.000000   0.640000 (  0.646360)
# ["foofoofoofoofoofoo=barbarbarbarbarbar", "bazbazbazbazbazbaz=quxquxquxquxquxqux", "foofoofoofoofoofoo=barbarbarbarbarbar"]
# ["foofoofoofoofoofoo=barbarbarbarbarbar", "bazbazbazbazbazbaz=quxquxquxquxquxqux", "foofoofoofoofoofoo=barbarbarbarbarbar"]
# ["foofoofoofoofoofoo=barbarbarbarbarbar", "bazbazbazbazbazbaz=quxquxquxquxquxqux", "foofoofoofoofoofoo=barbarbarbarbarbar"]
# ["foofoofoofoofoofoo=barbarbarbarbarbar", "bazbazbazbazbazbaz=quxquxquxquxquxqux", "foofoofoofoofoofoo=barbarbarbarbarbar"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment