Skip to content

Commit fec72c9

Browse files
committed
Speedup of __add_triple_context
1 parent a9aaef1 commit fec72c9

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

rdflib/plugins/stores/memory.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,6 @@ def add(self, triple, context, quoted=False):
222222
if context is not None:
223223
self.__all_contexts.add(context)
224224
subject, predicate, object_ = triple
225-
self.__add_triple_context(triple, context, quoted)
226225

227226
spo = self.__spo
228227
try:
@@ -233,7 +232,19 @@ def add(self, triple, context, quoted=False):
233232
o = po[predicate]
234233
except LookupError:
235234
o = po[predicate] = {}
236-
o[object_] = 1
235+
236+
try:
237+
_ = o[object_]
238+
# This cannot be reached if (s, p, o) was not inserted before.
239+
triple_exists = True
240+
except KeyError:
241+
o[object_] = 1
242+
triple_exists = False
243+
self.__add_triple_context(triple, triple_exists, context, quoted)
244+
245+
if triple_exists:
246+
# No need to insert twice this triple.
247+
return
237248

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

438449
# internal utility methods below
439-
def __add_triple_context(self, triple, context, quoted):
450+
def __add_triple_context(self, triple, triple_exists, context, quoted):
440451
"""add the given context to the set of contexts for the triple"""
441452
ctx = self.__ctx_to_str(context)
442453
quoted = bool(quoted)
443-
try:
444-
subj, pred, obj = triple
445-
_ = self.__spo[subj][pred][obj]
454+
if triple_exists:
446455
# we know the triple exists somewhere in the store
447456
try:
448457
triple_context = self.__tripleContexts[triple]
@@ -456,7 +465,7 @@ def __add_triple_context(self, triple, context, quoted):
456465
if not quoted:
457466
triple_context[None] = quoted
458467

459-
except KeyError:
468+
else:
460469
# the triple didn't exist before in the store
461470
if quoted: # this context only
462471
triple_context = self.__tripleContexts[triple] = {ctx: quoted}

0 commit comments

Comments
 (0)