From 9312ec1734fabac573bfb292dae4270c9a33e78c Mon Sep 17 00:00:00 2001
From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com>
Date: Fri, 24 Jun 2022 19:35:58 +0000
Subject: [PATCH] Move QPY version regex construction to import time (#8235)
 (#8240)

* Move QPY version regex construction to import time

As pointed out by @nkanazawa1989 in #8232 the regex construction added
to the QPY interface functions in #8200 can be a significant portion of
the overall function time especially for smaller inputs. Especially as
we're building it on every call interface function call. To ameliorate
that cost this commit compiles the version regex a single time at the
module level. This adds the overhead to import but it will only be done
once which should be a net improvement in performance.

* Fix regex flags usage

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
(cherry picked from commit ebf800a0e89dca878fa917d885bbb3e3a9be0d83)

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
---
 qiskit/qpy/interface.py | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/qiskit/qpy/interface.py b/qiskit/qpy/interface.py
index 02012452abfc..2e764e68bb70 100644
--- a/qiskit/qpy/interface.py
+++ b/qiskit/qpy/interface.py
@@ -69,6 +69,7 @@
 """
     + "$"
 )
+VERSION_PATTERN_REGEX = re.compile(VERSION_PATTERN, re.VERBOSE | re.IGNORECASE)
 
 
 @deprecate_arguments({"circuits": "programs"})
@@ -149,7 +150,7 @@ def dump(
     else:
         raise TypeError(f"'{program_type}' is not supported data type.")
 
-    version_match = re.search(VERSION_PATTERN, __version__, re.VERBOSE | re.IGNORECASE)
+    version_match = VERSION_PATTERN_REGEX.search(__version__)
     version_parts = [int(x) for x in version_match.group("release").split(".")]
     header = struct.pack(
         formats.FILE_HEADER_PACK,
@@ -226,7 +227,7 @@ def load(
     )
     if data.preface.decode(common.ENCODE) != "QISKIT":
         raise QiskitError("Input file is not a valid QPY file")
-    version_match = re.search(VERSION_PATTERN, __version__, re.VERBOSE | re.IGNORECASE)
+    version_match = VERSION_PATTERN_REGEX.search(__version__)
     version_parts = [int(x) for x in version_match.group("release").split(".")]
 
     header_version_parts = [data.major_version, data.minor_version, data.patch_version]