Skip to content

Commit a485ea5

Browse files
committed
improve performance for skip
1 parent 07331ae commit a485ea5

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

lib/json_mend/parser.rb

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ class Parser
1010
COMMENT_DELIMETERS = ['#', '/'].freeze
1111
NUMBER_CHARS = Set.new('0123456789-.eE/,_'.chars).freeze
1212
STRING_DELIMITERS = ['"', "'", '“', '”'].freeze
13+
SKIP_CHARS_REGEX_CACHE = {
14+
'"' => /"/,
15+
"'" => /'/,
16+
'“' => /“/,
17+
'”' => /”/,
18+
':' => /:/,
19+
'}' => /\}/
20+
}.freeze
1321
ESCAPE_MAPPING = {
1422
't' => "\t",
1523
'n' => "\n",
@@ -1085,11 +1093,14 @@ def parse_comment
10851093
end
10861094

10871095
# This function is a non-destructive lookahead.
1088-
# It quickly iterates to find a character, handling escaped characters, and
1096+
# It quickly iterates to find a character, handling escaped character, and
10891097
# returns the index (offset) from the scanner
10901098
def skip_to_character(characters, start_idx: 0)
1091-
chars = Array(characters).map { |c| Regexp.escape(c.to_s) }
1092-
pattern = Regexp.new(chars.join('|'))
1099+
pattern = SKIP_CHARS_REGEX_CACHE.fetch(characters, nil)
1100+
if pattern.nil?
1101+
chars = Array(characters).map { |c| Regexp.escape(c.to_s) }
1102+
pattern = Regexp.new(chars.join('|'))
1103+
end
10931104

10941105
saved_pos = @scanner.pos
10951106
# Skip start_idx

0 commit comments

Comments
 (0)