From fec72c964f57eb2fc80dac626f537fdc3aa62752 Mon Sep 17 00:00:00 2001 From: Remi Chateauneu Date: Mon, 17 May 2021 16:48:41 +0100 Subject: [PATCH] Speedup of __add_triple_context --- rdflib/plugins/stores/memory.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/rdflib/plugins/stores/memory.py b/rdflib/plugins/stores/memory.py index 8bf40a213..3baa629d5 100644 --- a/rdflib/plugins/stores/memory.py +++ b/rdflib/plugins/stores/memory.py @@ -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: @@ -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: @@ -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] @@ -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}