From b0ae75251272a05e832f52c73ab197979b4ba578 Mon Sep 17 00:00:00 2001 From: Alex Piechowski Date: Tue, 8 Feb 2022 20:35:34 -0600 Subject: [PATCH] Change ForceSSLHandler#secure? to use == instead of regex MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It's more clear and 52x faster in majority of scenarios (matches) and 24x faster on redirects (mismatches) It also does remove case insensitive searching, but it discussion on the PR #1662 stated this should be okay functionality to change Benchmark: ```crystal require "benchmark" puts "Matches" Benchmark.ips do |x| x.report("String ==") do "https" == "https" end x.report("!! String =~ /https/i") do !!("https" =~ /https/i) end end puts "\n\nMismatches" Benchmark.ips do |x| x.report("String == mismatch") do "http" == "https" end x.report("!! String =~ /https/i mismatch") do !!("http" =~ /https/i) end end ``` ```plaintext ➜ tmp crystal build --release downcase-includes-vs-regex.cr && ./downcase-includes-vs-regex Matches String == 897.53M ( 1.11ns) (± 6.76%) 0.0B/op fastest !! String =~ /https/i 17.13M ( 58.36ns) (±16.32%) 16.0B/op 52.38× slower Mismatches String == mismatch 881.32M ( 1.13ns) (± 8.78%) 0.0B/op fastest !! String =~ /https/i mismatch 36.42M ( 27.46ns) (± 1.47%) 16.0B/op 24.20× slower ``` --- src/lucky/force_ssl_handler.cr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lucky/force_ssl_handler.cr b/src/lucky/force_ssl_handler.cr index e3d186603..3abf7654f 100644 --- a/src/lucky/force_ssl_handler.cr +++ b/src/lucky/force_ssl_handler.cr @@ -48,7 +48,7 @@ class Lucky::ForceSSLHandler end private def secure?(context) : Bool - !!(context.request.headers["X-Forwarded-Proto"]? =~ /https/i) + context.request.headers["X-Forwarded-Proto"]? == "https" end private def redirect_to_secure_version(context : HTTP::Server::Context)