Created
March 2, 2011 03:06
-
-
Save kwatch/850396 to your computer and use it in GitHub Desktop.
benchmark to measure both h() and escape_html()
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
### | |
### benchmark to measure both h() and escape_html() | |
### | |
require 'rubygems' | |
require 'benchmarker' | |
ESCAPE_ = { | |
'&' => '&', | |
'<' => '<', | |
'>' => '>', | |
'"' => '"', | |
} | |
def h(s) | |
s.to_s.gsub(/[&<>"]/) { ESCAPE_[$&] } | |
end | |
def escape_html(s) | |
s.gsub(/&/, '&').gsub(/</, '<').gsub(/>/, '>').gsub(/"/, '"') | |
end | |
nloop = 1000*1000 | |
Benchmarker.new(:width=>30, :cycle=>5, :extra=>1, :barchart=>false) do |bm| | |
s1 = "Haruhi Mikuru Yuki Kyon Itsuki" | |
bm.task("h(s1)") do | |
nloop.times { h(s1) } | |
end | |
bm.task("escape_html(s1)") do | |
nloop.times { escape_html(s1) } | |
end | |
# | |
s2 = "Haruhi&Mikuru&Yuki&Kyon&Itsuki" | |
bm.task("h(s2)") do | |
nloop.times { h(s2) } | |
end | |
bm.task("escape_html(s2)") do | |
nloop.times { escape_html(s2) } | |
end | |
# | |
s3 = "<Haruhi>&<Mikuru>&<Yuki>&<Kyon>&<Itsuki>" | |
bm.task("h(s3)") do | |
nloop.times { h(s3) } | |
end | |
bm.task("escape_html(s3)") do | |
nloop.times { escape_html(s3) } | |
end | |
end | |
__END__ | |
# benchmarker.rb: release 0.0.0 | |
# RUBY_VERSION: 1.8.7 | |
# RUBY_PATCHLEVEL: 334 | |
# RUBY_PLATFORM: i686-darwin10.6.0 | |
# | |
# ## Ranking real | |
# h(s1) 1.6433 (100.0%) 0.61 times/sec | |
# escape_html(s1) 3.0330 ( 54.2%) 0.33 times/sec | |
# escape_html(s2) 9.4641 ( 17.4%) 0.11 times/sec | |
# h(s2) 12.6723 ( 13.0%) 0.08 times/sec | |
# escape_html(s3) 19.8207 ( 8.3%) 0.05 times/sec | |
# h(s3) 40.0310 ( 4.1%) 0.02 times/sec | |
# | |
# ## Matrix real [01] [02] [03] [04] [05] [06] | |
# [01] h(s1) 1.6433 100.0% 184.6% 575.9% 771.1% 1206.1% 2436.0% | |
# [02] escape_html(s1) 3.0330 54.2% 100.0% 312.0% 417.8% 653.5% 1319.8% | |
# [03] escape_html(s2) 9.4641 17.4% 32.0% 100.0% 133.9% 209.4% 423.0% | |
# [04] h(s2) 12.6723 13.0% 23.9% 74.7% 100.0% 156.4% 315.9% | |
# [05] escape_html(s3) 19.8207 8.3% 15.3% 47.7% 63.9% 100.0% 202.0% | |
# [06] h(s3) 40.0310 4.1% 7.6% 23.6% 31.7% 49.5% 100.0% |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment