Project

General

Profile

Bug #21856 » benchmark.rb

ahorek (Pavel Rosický), 02/01/2026 08:10 PM

 
# frozen_string_literal: true

require "benchmark"
require "loofah"
require "nokogiri"

HTML_INPUT = <<~HTML
<div class="post">
<h1 onclick="alert('xss')">Hello</h1>
<p>This is <strong>safe</strong> text.</p>
<script>alert("evil")</script>
<a href="javascript:alert('xss')">Click me</a>
<img src="x" onerror="alert('xss')">
</div>
HTML

ITERATIONS = 100_000

puts "Ruby: #{RUBY_VERSION}"
puts "Loofah: #{Loofah::VERSION}"
puts "Nokogiri: #{Nokogiri::VERSION}"
puts "Iterations: #{ITERATIONS}"
puts

Benchmark.bm(35) do |x|
x.report("Loofah.fragment + scrub!(:prune)") do
ITERATIONS.times do
Loofah.fragment(HTML_INPUT).scrub!(:prune).to_s
end
end

x.report("Loofah.scrub_fragment(:prune)") do
ITERATIONS.times do
Loofah.scrub_fragment(HTML_INPUT, :prune).to_s
end
end

x.report("Nokogiri HTML parse only") do
ITERATIONS.times do
Nokogiri::HTML.fragment(HTML_INPUT)
end
end
end
    (1-1/1)