Skip to content

Instantly share code, notes, and snippets.

@kwatch
Created March 2, 2011 03:12
Show Gist options
  • Save kwatch/850402 to your computer and use it in GitHub Desktop.
Save kwatch/850402 to your computer and use it in GitHub Desktop.
benchmark to measure CGI::parse()
# -*- coding: utf-8 -*-
###
### benchmark to measure CGI::parse()
###
require 'rubygems'
require 'benchmarker'
require 'cgi'
name = '涼宮ハルヒ'
comment = 'ただの人間には興味ありません。'
query = "comment.name=#{CGI.escape(name)}&comment.body=#{CGI.escape(comment)}"
class CGI
def CGI::parse1(query)
params = {}
query.split(/[&;]/n).each do |pairs|
key, val = pairs.split(/=/, 2) \
.collect {|v| CGI::unescape(v) }
(params[key] ||= []) << val
end
params
end
def CGI::parse2(query)
params = {}
query.split(/[&;]/n).each do |pairs|
key, val = pairs.split(/=/, 2)
key = CGI::unescape(key)
val = CGI::unescape(val)
(params[key] ||= []) << val
end
params
end
def CGI::parse3(query)
params = {}
query.split(/[&;]/n).each do |pairs|
key, val = pairs.split(/=/, 2)
key = CGI::unescape(key) if key =~ /%/
val = CGI::unescape(val)
(params[key] ||= []) << val
end
params
end
end
nloop = 100*1000
Benchmarker.new(:cycle=>5, :extra=>1) do |bm|
bm.task("CGI::parse1()") do
nloop.times { CGI::parse1(query) }
end
bm.task("CGI::parse2()") do
nloop.times { CGI::parse2(query) }
end
bm.task("CGI::parse3()") do
nloop.times { CGI::parse3(query) }
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
# CGI::parse3() 5.5837 (100.0%) ********************
# CGI::parse2() 5.8492 ( 95.5%) *******************
# CGI::parse1() 6.1806 ( 90.3%) ******************
# benchmarker.rb: release 0.0.0
# RUBY_VERSION: 1.9.2
# RUBY_PATCHLEVEL: 180
# RUBY_PLATFORM: x86_64-darwin10.6.0
#
# ## Ranking real
# CGI::parse3() 6.7640 (100.0%) ********************
# CGI::parse2() 7.2005 ( 93.9%) *******************
# CGI::parse1() 7.3592 ( 91.9%) ******************
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment