From cdc707fa38c39b7c4a97b37026a67759a65a83d4 Mon Sep 17 00:00:00 2001 From: Ian Gregory Date: Thu, 27 Oct 2022 01:28:08 -0400 Subject: [PATCH] Cache compiled regexes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Improves performance of `brew info --json=v2 --eval-all` by about 15–20% --- Library/Homebrew/cask/cask_loader.rb | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/Library/Homebrew/cask/cask_loader.rb b/Library/Homebrew/cask/cask_loader.rb index 8049077ee6..93ac87bb9b 100644 --- a/Library/Homebrew/cask/cask_loader.rb +++ b/Library/Homebrew/cask/cask_loader.rb @@ -19,12 +19,15 @@ module Cask content = ref.to_str - token = /(?:"[^"]*"|'[^']*')/ - curly = /\(\s*#{token.source}\s*\)\s*\{.*\}/ - do_end = /\s+#{token.source}\s+do(?:\s*;\s*|\s+).*end/ - regex = /\A\s*cask(?:#{curly.source}|#{do_end.source})\s*\Z/m + # Cache compiled regex + @regex ||= begin + token = /(?:"[^"]*"|'[^']*')/ + curly = /\(\s*#{token.source}\s*\)\s*\{.*\}/ + do_end = /\s+#{token.source}\s+do(?:\s*;\s*|\s+).*end/ + /\A\s*cask(?:#{curly.source}|#{do_end.source})\s*\Z/m + end - content.match?(regex) + content.match?(@regex) end def initialize(content) @@ -93,8 +96,13 @@ module Cask extend T::Sig def self.can_load?(ref) - uri_regex = ::URI::DEFAULT_PARSER.make_regexp - return false unless ref.to_s.match?(Regexp.new("\\A#{uri_regex.source}\\Z", uri_regex.options)) + # Cache compiled regex + @uri_regex ||= begin + uri_regex = ::URI::DEFAULT_PARSER.make_regexp + Regexp.new("\\A#{uri_regex.source}\\Z", uri_regex.options) + end + + return false unless ref.to_s.match?(@uri_regex) uri = URI(ref) return false unless uri