From d0295f3168945be0af75be0660f474d0aa2f5087 Mon Sep 17 00:00:00 2001 From: Albert Vaca Date: Thu, 20 Jun 2019 16:36:27 +0200 Subject: [PATCH] Do not compile regexes on each run (#3949) * Do not compile regexes on each run - Keep a cache of already compiled regexes (they will always be the same) - Alphanumeric strings an be simply matched for `==` instead of using RE. * Deduplicate loop as per CR --- .../datadog_checks/go_expvar/go_expvar.py | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/go_expvar/datadog_checks/go_expvar/go_expvar.py b/go_expvar/datadog_checks/go_expvar/go_expvar.py index 83dbb78d016aa..6871c6a710dfd 100644 --- a/go_expvar/datadog_checks/go_expvar/go_expvar.py +++ b/go_expvar/datadog_checks/go_expvar/go_expvar.py @@ -63,6 +63,7 @@ class GoExpvar(AgentCheck): def __init__(self, name, init_config, agentConfig, instances=None): AgentCheck.__init__(self, name, init_config, agentConfig, instances) + self._regexes = {} self._last_gc_count = defaultdict(int) def _get_data(self, url, instance): @@ -227,16 +228,26 @@ def deep_get(self, content, keys, traversed_path=None): return [(traversed_path, content)] key = keys[0] - regex = "".join(["^", key, "$"]) - try: - key_rex = re.compile(regex) - except Exception: - self.warning("Cannot compile regex: %s" % regex) - return [] + if key.isalnum(): + # key is not a regex, simply match for equality + matcher = key.__eq__ + else: + # key might be a regex + key_regex = self._regexes.get(key) + if key_regex is None: + # we don't have it cached, compile it + regex = "^{}$".format(key) + try: + key_regex = re.compile(regex) + except Exception: + self.warning("Cannot compile regex: %s" % regex) + return [] + self._regexes[key] = key_regex + matcher = key_regex.match results = [] for new_key, new_content in self.items(content): - if key_rex.match(new_key): + if matcher(new_key): results.extend(self.deep_get(new_content, keys[1:], traversed_path + [str(new_key)])) return results