mirror of
https://github.com/nmap/nmap.git
synced 2025-12-09 06:01:28 +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:
@@ -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):
|
class StringPoolTest(unittest.TestCase):
|
||||||
"""Return a single unique representation of s (unique as to id),
|
|
||||||
letting s be garbage collected."""
|
def test_pool(self):
|
||||||
return UNIQUE_STRING_MAP.setdefault(s, s)
|
source = "Test string. Zenmap. Test string."
|
||||||
|
self.assertIs(unique(source[:12]), unique(source[-12:]))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
|
|||||||
Reference in New Issue
Block a user