From f448e2b9951e1893df9741e21dd9a786d2ca020c Mon Sep 17 00:00:00 2001 From: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Wed, 26 Nov 2025 16:13:04 +0100 Subject: [PATCH] Optimize `Prism::Source#find_line` This is more concise and ruby does a better job performance-wise. This used to be `bsearch_index` already but https://github.com/ruby/prism/commit/6d8358c08395438d5924777c1fc3001a5ebf0aa3 changed it. https://github.com/ruby/prism/pull/1733#discussion_r1373702087 said: > Yeah the edge case was that the value matched an element exactly But surely there would be a test to show this behaviour? Gets called as part of pretty-printing nodes. Further reduces the time for `SnapshotsTest` by ~16% for me. --- lib/prism/parse_result.rb | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/lib/prism/parse_result.rb b/lib/prism/parse_result.rb index 05c14e33f5..3570af136a 100644 --- a/lib/prism/parse_result.rb +++ b/lib/prism/parse_result.rb @@ -155,21 +155,8 @@ def deep_freeze # Binary search through the offsets to find the line number for the given # byte offset. def find_line(byte_offset) - left = 0 - right = offsets.length - 1 - - while left <= right - mid = left + (right - left) / 2 - return mid if (offset = offsets[mid]) == byte_offset - - if offset < byte_offset - left = mid + 1 - else - right = mid - 1 - end - end - - left - 1 + index = offsets.bsearch_index { |offset| offset > byte_offset } || offsets.length + index - 1 end end