Last active
June 11, 2018 05:10
-
-
Save hbin/c2f6e9203e1d17a6aaf7 to your computer and use it in GitHub Desktop.
Benchmark escape html methods
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/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
===== 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