Skip to content

Instantly share code, notes, and snippets.

@hbin
Last active June 11, 2018 05:10
Show Gist options
  • Save hbin/c2f6e9203e1d17a6aaf7 to your computer and use it in GitHub Desktop.
Save hbin/c2f6e9203e1d17a6aaf7 to your computer and use it in GitHub Desktop.
Benchmark escape html methods
require 'benchmark/ips'
require 'open-uri'
require 'cgi'
require 'erb'
require 'rack'
puts "===== Short String =====\n\n"
Benchmark.ips do |x|
SHORT_STR = %(<html><head></head><body></body></html>)
x.report 'CGI::escapeHTML' do
CGI::escapeHTML SHORT_STR
end
x.report 'ERB::Util.html_escape' do
ERB::Util.html_escape SHORT_STR
end
x.report 'Rack::Utils.escape_html' do
Rack::Utils.escape_html SHORT_STR
end
x.compare!
end
puts "===== Long String =====\n\n"
Benchmark.ips do |x|
LONG_STR = open('http://example.com/').read
x.report 'CGI::escapeHTML' do
CGI::escapeHTML LONG_STR
end
x.report 'ERB::Util.html_escape' do
ERB::Util.html_escape LONG_STR
end
x.report 'Rack::Utils.escape_html' do
Rack::Utils.escape_html LONG_STR
end
x.compare!
end
require 'active_support/core_ext/string'
puts "===== Short HTML Safe String =====\n\n"
Benchmark.ips do |x|
SHORT_HTML_SAFE_STR = %(<html><head></head><body></body></html>).html_safe
x.report 'CGI::escapeHTML' do
CGI::escapeHTML SHORT_HTML_SAFE_STR
end
x.report 'ERB::Util.html_escape' do
ERB::Util.html_escape SHORT_HTML_SAFE_STR
end
x.report 'Rack::Utils.escape_html' do
Rack::Utils.escape_html SHORT_HTML_SAFE_STR
end
x.compare!
end
puts "===== Long HTML Safe String =====\n\n"
Benchmark.ips do |x|
LONG_HTML_SAFE_STR = open('http://example.com/').read.html_safe
x.report 'CGI::escapeHTML' do
CGI::escapeHTML LONG_HTML_SAFE_STR
end
x.report 'ERB::Util.html_escape' do
ERB::Util.html_escape LONG_HTML_SAFE_STR
end
x.report 'Rack::Utils.escape_html' do
Rack::Utils.escape_html LONG_HTML_SAFE_STR
end
x.compare!
end
@hbin
Copy link
Author

hbin commented Jun 27, 2014

===== Short String =====
Comparison:
ERB::Util.html_escape: 113217.7 i/s
CGI::escapeHTML: 110218.2 i/s - 1.03x slower
Rack::Utils.escape_html: 81503.8 i/s - 1.39x slower

===== Long String =====
Comparison:
ERB::Util.html_escape: 25110.7 i/s
CGI::escapeHTML: 24430.1 i/s - 1.03x slower
Rack::Utils.escape_html: 16207.2 i/s - 1.55x slower

===== Short HTML Safe String =====
Comparison:
ERB::Util.html_escape: 2772776.1 i/s
CGI::escapeHTML: 106256.2 i/s - 26.10x slower
Rack::Utils.escape_html: 72086.8 i/s - 38.46x slower

===== Long HTML Safe String =====
Comparison:
ERB::Util.html_escape: 2749941.1 i/s
CGI::escapeHTML: 24777.1 i/s - 110.99x slower
Rack::Utils.escape_html: 16229.5 i/s - 169.44x slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment