Skip to content

Commit afcf3fc

Browse files
committed
Micro-optimize Router#find_routes
`each_with_index` is unfortunately a noticeably slower than `each`, especially when YJIT is enabled. By incrementing the index ourselves we can squeeze a little bit of performance in that hotspot. Followup: rails#54504 Followup: rails#54491 Followup: rails#54505 Followup: rails#54515 Same benchmark as: rails#54491 (comment) ``` == index == ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +YJIT +PRISM [arm64-darwin23] Warming up -------------------------------------- after 45.667k i/100ms Calculating ------------------------------------- after 480.940k (± 0.9%) i/s (2.08 μs/i) - 2.420M in 5.032946s Comparison: before: 458171.4 i/s after: 480939.8 i/s - 1.05x faster == show == ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +YJIT +PRISM [arm64-darwin23] Warming up -------------------------------------- after 37.524k i/100ms Calculating ------------------------------------- after 374.480k (± 0.7%) i/s (2.67 μs/i) - 1.876M in 5.010385s Comparison: before: 358267.3 i/s after: 374479.9 i/s - 1.05x faster == show_nested == ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +YJIT +PRISM [arm64-darwin23] Warming up -------------------------------------- after 35.187k i/100ms Calculating ------------------------------------- after 353.827k (± 0.7%) i/s (2.83 μs/i) - 1.795M in 5.072038s Comparison: before: 336299.6 i/s after: 353827.3 i/s - 1.05x faster ```
1 parent 1142fd4 commit afcf3fc

File tree

1 file changed

+7
-5
lines changed
  • actionpack/lib/action_dispatch/journey

1 file changed

+7
-5
lines changed

actionpack/lib/action_dispatch/journey/router.rb

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,15 +118,17 @@ def find_routes(req)
118118

119119
routes.sort_by!(&:precedence)
120120

121-
routes.each { |r|
121+
routes.each do |r|
122122
match_data = r.path.match(path_info)
123123
path_parameters = {}
124-
match_data.names.each_with_index { |name, i|
125-
val = match_data[i + 1]
124+
index = 1
125+
match_data.names.each do |name|
126+
val = match_data[index]
126127
path_parameters[name.to_sym] = Utils.unescape_uri(val) if val
127-
}
128+
index += 1
129+
end
128130
yield [match_data, path_parameters, r]
129-
}
131+
end
130132
end
131133

132134
def match_head_routes(routes, req)

0 commit comments

Comments
 (0)