Skip to content

Commit

Permalink
Improve the performances of SqliteDb._connect
Browse files Browse the repository at this point in the history
Since the self.filename attribute doesn't change
during the lifetime of a SqliteDb object,
we can move its relpath transformation in
the init method, instead of doing it every time
_connect is called, resulting in a ~30% performances
gain.
  • Loading branch information
jvoisin authored and nedbat committed Jan 4, 2020
1 parent aefe08b commit aa6d851
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions coverage/sqldata.py
Expand Up @@ -971,30 +971,31 @@ def __init__(self, filename, debug):
self.filename = filename
self.nest = 0
self.con = None

def _connect(self):
"""Connect to the db and do universal initialization."""
if self.con is not None:
return
# SQLite on Windows on py2 won't open a file if the filename argument
# has non-ascii characters in it. Opening a relative file name avoids
# a problem if the current directory has non-ascii.
try:
filename = os.path.relpath(self.filename)
self.connect_filename = os.path.relpath(self.filename)
except ValueError:
# ValueError can be raised under Windows when os.getcwd() returns a
# folder from a different drive than the drive of self.filename in
# which case we keep the original value of self.filename unchanged,
# hoping that we won't face the non-ascii directory problem.
filename = self.filename
self.connect_filename = self.filename

def _connect(self):
"""Connect to the db and do universal initialization."""
if self.con is not None:
return

# It can happen that Python switches threads while the tracer writes
# data. The second thread will also try to write to the data,
# effectively causing a nested context. However, given the idempotent
# nature of the tracer operations, sharing a connection among threads
# is not a problem.
if self.debug:
self.debug.write("Connecting to {!r}".format(self.filename))
self.con = sqlite3.connect(filename, check_same_thread=False)
self.con = sqlite3.connect(self.connect_filename, check_same_thread=False)
self.con.create_function('REGEXP', 2, _regexp)

# This pragma makes writing faster. It disables rollbacks, but we never need them.
Expand Down

0 comments on commit aa6d851

Please sign in to comment.