From 55c7fb605fe37eda250b3efe9683f6b491000028 Mon Sep 17 00:00:00 2001 From: dmiller Date: Wed, 15 Jan 2014 15:37:25 +0000 Subject: [PATCH] Improve performance of StringPool.unique This saves a function call by using subclassing dict instead of using a real dict. When a cache hit occurs, there is no overhead beyond a standard dict lookup, which in most implementations is very fast. Cache miss is similar performance to previous. Also added a unittest for this functionality. --- zenmap/zenmapCore/StringPool.py | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/zenmap/zenmapCore/StringPool.py b/zenmap/zenmapCore/StringPool.py index e4573313b..63a69bf64 100644 --- a/zenmap/zenmapCore/StringPool.py +++ b/zenmap/zenmapCore/StringPool.py @@ -120,10 +120,26 @@ # * * # ***************************************************************************/ -UNIQUE_STRING_MAP = {} + +class UniqueStringMap(dict): + def __missing__(self, key): + self[key] = key + return key + +UNIQUE_STRING_MAP = UniqueStringMap() + +# Return a single unique representation of s (unique as to id), +# letting s be garbage collected. +unique = UNIQUE_STRING_MAP.__getitem__ + +import unittest -def unique(s): - """Return a single unique representation of s (unique as to id), - letting s be garbage collected.""" - return UNIQUE_STRING_MAP.setdefault(s, s) +class StringPoolTest(unittest.TestCase): + + def test_pool(self): + source = "Test string. Zenmap. Test string." + self.assertIs(unique(source[:12]), unique(source[-12:])) + +if __name__ == '__main__': + unittest.main()