1
0
mirror of https://github.com/nmap/nmap.git synced 2025-12-07 05:01:29 +00:00

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.
This commit is contained in:
dmiller
2014-01-15 15:37:25 +00:00
parent 2b2edabc80
commit 55c7fb605f

View File

@@ -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()