Skip to content

Commit

Permalink
Merge pull request #1320 from rchateauneu/speedup_add_triple_context
Browse files Browse the repository at this point in the history
Speedup of __add_triple_context
  • Loading branch information
nicholascar committed Jun 26, 2021
2 parents a83aa06 + fec72c9 commit 69320ab
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions rdflib/plugins/stores/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,6 @@ def add(self, triple, context, quoted=False):
if context is not None:
self.__all_contexts.add(context)
subject, predicate, object_ = triple
self.__add_triple_context(triple, context, quoted)

spo = self.__spo
try:
Expand All @@ -233,7 +232,19 @@ def add(self, triple, context, quoted=False):
o = po[predicate]
except LookupError:
o = po[predicate] = {}
o[object_] = 1

try:
_ = o[object_]
# This cannot be reached if (s, p, o) was not inserted before.
triple_exists = True
except KeyError:
o[object_] = 1
triple_exists = False
self.__add_triple_context(triple, triple_exists, context, quoted)

if triple_exists:
# No need to insert twice this triple.
return

pos = self.__pos
try:
Expand Down Expand Up @@ -436,13 +447,11 @@ def remove_graph(self, graph):
pass # we didn't know this graph, no problem

# internal utility methods below
def __add_triple_context(self, triple, context, quoted):
def __add_triple_context(self, triple, triple_exists, context, quoted):
"""add the given context to the set of contexts for the triple"""
ctx = self.__ctx_to_str(context)
quoted = bool(quoted)
try:
subj, pred, obj = triple
_ = self.__spo[subj][pred][obj]
if triple_exists:
# we know the triple exists somewhere in the store
try:
triple_context = self.__tripleContexts[triple]
Expand All @@ -456,7 +465,7 @@ def __add_triple_context(self, triple, context, quoted):
if not quoted:
triple_context[None] = quoted

except KeyError:
else:
# the triple didn't exist before in the store
if quoted: # this context only
triple_context = self.__tripleContexts[triple] = {ctx: quoted}
Expand Down

0 comments on commit 69320ab

Please sign in to comment.