Do not allocate the first path character in asset helper

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
This commit is contained in:
Nicolò Rebughini 2023-03-20 17:32:42 +01:00
parent 25f8d57100
commit a63ae913df

@ -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