Last active
December 17, 2015 08:29
-
-
Save stim371/5580318 to your computer and use it in GitHub Desktop.
benchmarking different options for splitting a string
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
require 'benchmark' | |
str = "1234 Ocean Drive #PH 2" | |
n = 50000 | |
def split_arr(str) | |
str.split('#')[0] | |
end | |
def slice_index(str) | |
str.slice(0..(str.index('#')-1)) | |
end | |
def slice_regex(str) | |
str.slice(/.*#/).chop() | |
end | |
def slice_regex2(str) | |
str.slice(/.*#/)[0..-2] | |
end | |
def regex_index(str) | |
str[/[^#]+/] | |
end | |
def regex(str) | |
str.match(/.*#/)[1] | |
end | |
Benchmark.bmbm do |x| | |
x.report("split_arr:") { n.times do; split_arr(str); end } | |
x.report("slice_index:") { n.times do; slice_index(str); end } | |
x.report("slice_regex:") { n.times do; slice_regex(str); end } | |
x.report("slice_regex2:") { n.times do; slice_regex2(str); end } | |
x.report("regex_index:") { n.times do; regex_index(str); end } | |
x.report("regex:") { n.times do; regex(str); end } | |
end | |
# RESULTS | |
# --------------------------------- | |
# user system total real | |
# split_arr: 0.030000 0.000000 0.030000 ( 0.029324) | |
# slice_index: 0.040000 0.000000 0.040000 ( 0.042199) | |
# slice_regex: 0.080000 0.000000 0.080000 ( 0.075515) | |
# slice_regex2: 0.080000 0.000000 0.080000 ( 0.080026) | |
# regex_index: 0.070000 0.000000 0.070000 ( 0.072073) | |
# regex: 0.090000 0.000000 0.090000 ( 0.087584) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment