From a63ae913dfbb3813256144e52ae1063ac59edba4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Rebughini?= Date: Mon, 20 Mar 2023 17:32:42 +0100 Subject: [PATCH] Do not allocate the first path character in asset helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In asset heavy views, the asset_path helper might be called a lot of times. When checking the first character of the source element with [] we allocate a string each time just to check it against ?/. By using String#start_with? we can avoid this step and go a bit faster. This is the code I used to measure the change: ``` 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("source[0]") do TEST_PATH[0] != ROOT_STRING end x.report("source.start_with?") do TEST_PATH.start_with?(ROOT_STRING) end x.compare! end ``` Warming up -------------------------------------- source[0] 905.322k i/100ms source.start_with? 1.541M i/100ms Calculating ------------------------------------- source[0] 9.012M (± 0.7%) i/s - 45.266M in 5.022969s source.start_with? 15.395M (± 0.4%) i/s - 77.030M in 5.003691s Comparison: source.start_with?: 15394807.0 i/s source[0]: 9012304.9 i/s - 1.71x slower --- actionview/lib/action_view/helpers/asset_url_helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionview/lib/action_view/helpers/asset_url_helper.rb b/actionview/lib/action_view/helpers/asset_url_helper.rb index 72ca5fe04f..6ee75f580c 100644 --- a/actionview/lib/action_view/helpers/asset_url_helper.rb +++ b/actionview/lib/action_view/helpers/asset_url_helper.rb @@ -196,7 +196,7 @@ def asset_path(source, options = {}) source = "#{source}#{extname}" end - if source[0] != ?/ + unless source.start_with?(?/) if options[:skip_pipeline] source = public_compute_asset_path(source, options) else