From 4fbf6ceeec8aa8c5d0ef0ae5063a2a64f40a348e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Csord=C3=A1s?= Date: Thu, 18 Feb 2021 16:55:52 +0100 Subject: [PATCH] [ref] Use singleton when creating context objects Use singleton pattern when creating context objects (analyzer/web) to improve the performance. --- analyzer/codechecker_analyzer/analyzer_context.py | 3 ++- codechecker_common/singleton.py | 11 +++++++++++ web/codechecker_web/shared/webserver_context.py | 3 ++- 3 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 codechecker_common/singleton.py diff --git a/analyzer/codechecker_analyzer/analyzer_context.py b/analyzer/codechecker_analyzer/analyzer_context.py index db7540c02c..68b4b3f882 100644 --- a/analyzer/codechecker_analyzer/analyzer_context.py +++ b/analyzer/codechecker_analyzer/analyzer_context.py @@ -18,6 +18,7 @@ import sys from codechecker_common import logger +from codechecker_common.singleton import Singleton from codechecker_common.util import load_json_or_empty from . import env @@ -247,7 +248,7 @@ def available_guidelines(self): # ----------------------------------------------------------------------------- -class Context(object): +class Context(object, metaclass=Singleton): """ Generic package specific context. """ def __init__(self, package_root, pckg_layout, cfg_dict): diff --git a/codechecker_common/singleton.py b/codechecker_common/singleton.py new file mode 100644 index 0000000000..ab21047c03 --- /dev/null +++ b/codechecker_common/singleton.py @@ -0,0 +1,11 @@ +class Singleton(type): + """ Helper type to create singleton classes. """ + + _instances = {} + + def __call__(cls, *args, **kwargs): + if cls not in cls._instances: + cls._instances[cls] = \ + super(Singleton, cls).__call__(*args, **kwargs) + + return cls._instances[cls] diff --git a/web/codechecker_web/shared/webserver_context.py b/web/codechecker_web/shared/webserver_context.py index 2f51cb4ca5..97d66a96ed 100644 --- a/web/codechecker_web/shared/webserver_context.py +++ b/web/codechecker_web/shared/webserver_context.py @@ -15,6 +15,7 @@ import sys from codechecker_common import logger +from codechecker_common.singleton import Singleton from codechecker_common.util import load_json_or_empty LOG = logger.get_logger('system') @@ -49,7 +50,7 @@ def __len__(self): # ----------------------------------------------------------------------------- -class Context(object): +class Context(object, metaclass=Singleton): """ Generic package specific context. """ def __init__(self, package_root, pckg_layout, cfg_dict):