Skip to content

[ruby] Use Rack::Utils.escape_html for escaping #10032

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

p8
Copy link
Contributor

@p8 p8 commented Aug 5, 2025

Rack::Utils.escape_html is faster than CGI.escape_html:

require 'benchmark/ips'
require 'cgi'
require 'rack'

Benchmark.ips do |x|
  x.config(warmup: 2, time: 5)

  message = 'Additional fortune added at request time.'
  x.report("CGI") do
    CGI.escape_html(message)
  end

  x.report("Rack") do
    Rack::Utils.escape_html(message)
  end

  x.compare!
end
ruby 3.4.4 (2025-05-14 revision a38531fd3f) +PRISM [arm64-darwin24]
Warming up --------------------------------------
                 CGI     1.016M i/100ms
                Rack     1.586M i/100ms
Calculating -------------------------------------
                 CGI     10.821M (± 0.3%) i/s   (92.42 ns/i) -     54.837M in   5.067830s
                Rack     15.861M (± 0.3%) i/s   (63.05 ns/i) -     80.886M in   5.099606s

Comparison:
                Rack: 15861352.0 i/s
                 CGI: 10820753.9 i/s - 1.47x  slower

Rack::Utils.escape_html is faster than CGI.escape_html:

```ruby
require 'benchmark/ips'
require 'cgi'
require 'rack'

Benchmark.ips do |x|
  x.config(warmup: 2, time: 5)

  message = 'Additional fortune added at request time.'
  x.report("CGI") do
    CGI.escape_html(message)
  end

  x.report("Rack") do
    Rack::Utils.escape_html(message)
  end

  x.compare!
end
```

```
ruby 3.4.4 (2025-05-14 revision a38531fd3f) +PRISM [arm64-darwin24]
Warming up --------------------------------------
                 CGI     1.016M i/100ms
                Rack     1.586M i/100ms
Calculating -------------------------------------
                 CGI     10.821M (± 0.3%) i/s   (92.42 ns/i) -     54.837M in   5.067830s
                Rack     15.861M (± 0.3%) i/s   (63.05 ns/i) -     80.886M in   5.099606s

Comparison:
                Rack: 15861352.0 i/s
                 CGI: 10820753.9 i/s - 1.47x  slower
```
@msmith-techempower msmith-techempower merged commit 6c26a89 into TechEmpower:master Aug 11, 2025
4 checks passed
@p8 p8 deleted the ruby/improve-html-escaping branch August 11, 2025 19:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants