From 14c6e04438d356e11e82269a8d79b96d9496543c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Rebughini?= Date: Wed, 22 Mar 2023 14:46:35 +0100 Subject: [PATCH] Do not allocate the first character when checking for relative paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is the same optimization applied in https://github.com/rails/rails/commit/a63ae913dfbb3813256144e52ae1063ac59edba4 which I proposed in https://github.com/rails/rails/pull/47714 Here's the benchmark: require "bundler/inline" ROOT_STRING = '/' TEST_PATH = "/some/path" gemfile(true) do source "https://rubygems.org" gem "benchmark-ips" end Benchmark.ips do |x| x.report("path[0]") do TEST_PATH[0] != ROOT_STRING end x.report("path.start_with?") do TEST_PATH.start_with?(ROOT_STRING) end x.compare! end Warming up -------------------------------------- path[0] 942.044k i/100ms path.start_with? 1.556M i/100ms Calculating ------------------------------------- path[0] 9.463M (± 0.9%) i/s - 48.044M in 5.077358s path.start_with? 15.611M (± 0.2%) i/s - 79.352M in 5.083056s Comparison: path.start_with?: 15611192.8 i/s path[0]: 9463245.0 i/s - 1.65x slower --- actionpack/lib/action_dispatch/routing/redirection.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb index 054798ec7d..0ae7ce7a68 100644 --- a/actionpack/lib/action_dispatch/routing/redirection.rb +++ b/actionpack/lib/action_dispatch/routing/redirection.rb @@ -68,7 +68,7 @@ def inspect private def relative_path?(path) - path && !path.empty? && path[0] != "/" + path && !path.empty? && !path.start_with?("/") end def escape(params)