Skip to content

Instantly share code, notes, and snippets.

@paul
Created August 1, 2011 20:54
Show Gist options
  • Save paul/1118977 to your computer and use it in GitHub Desktop.
Save paul/1118977 to your computer and use it in GitHub Desktop.
$ ruby split_vs_regex.rb
user system total real
split 9.080000 0.020000 9.100000 ( 9.081937)
regex 9.810000 0.010000 9.820000 ( 9.810586)
$ ruby split_vs_regex.rb
user system total real
split 3.776000 0.000000 3.776000 ( 3.731000)
regex 3.729000 0.000000 3.729000 ( 3.729000)
require 'date'
require 'time'
require 'benchmark'
def parse_by_split(str)
day, time = str.split(':', 2)
day, month, year = day.split('/')
month = Date::ABBR_MONTHNAMES.index(month)
hour, minute, second = time.split(':')
Time.utc(year.to_i, month.to_i, day.to_i, hour.to_i, minute.to_i, second.to_f)
end
REGEX = /(\d+)\/(\w+)\/(\d+):(\d+):(\d+):(\d+) (-?\d+)/
def parse_by_regex(str)
match = REGEX.match(str)
month = Date::ABBR_MONTHNAMES.index(match[2])
Time.utc(match[3].to_i, month, match[1].to_i, match[4].to_i, match[5].to_i, match[6].to_i)
end
STRING = "01/Aug/2011:13:26:51 -0700"
N = 1_000_000
Benchmark.bm(10) do |bm|
bm.report("split") do
N.times { parse_by_split(STRING) }
end
bm.report("regex") do
N.times { parse_by_regex(STRING) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment