Last active
February 20, 2016 18:19
-
-
Save jrunning/a5f814c9a880960d0139 to your computer and use it in GitHub Desktop.
trim_quotes.rb
This file contains hidden or 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/ips' | |
| require 'securerandom' | |
| def trim_quotes_wiktor(str) | |
| str.gsub(/\A"(.*)"\Z/m, '\1') | |
| end | |
| def trim_quotes_sawa(str) | |
| str.dup.tap do |s| | |
| s[0] = s[-1] = "" if s[0] == '"' and s[-1] == '"' | |
| end | |
| end | |
| # Generate a random string 4-52 characters in length with a 70% | |
| # chance of having a leading `"` and a 70% chance of having a | |
| # trailing `"`. | |
| RAND_SIZE = 4..50 | |
| def rand_str | |
| size = rand(RAND_SIZE) / 2 | |
| str = SecureRandom.hex(size) | |
| "#{?" if rand > 0.3}#{str}#{?" if rand > 0.3}" | |
| end | |
| data = Array.new(5000) { rand_str } | |
| Benchmark.ips do |x| | |
| x.report("wiktor") { data.each {|str| trim_quotes_wiktor(str) } } | |
| x.report("sawa") { data.each {|str| trim_quotes_sawa(str) } } | |
| x.compare! | |
| end |
This file contains hidden or 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
| Calculating ------------------------------------- | |
| wiktor 8.000 i/100ms | |
| sawa 23.000 i/100ms | |
| ------------------------------------------------- | |
| wiktor 69.514 (± 7.2%) i/s - 352.000 | |
| sawa 214.339 (± 9.3%) i/s - 1.081k | |
| Comparison: | |
| sawa: 214.3 i/s | |
| wiktor: 69.5 i/s - 3.08x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment