Skip to content

Commit 13887b5

Browse files
committed
Cache imported protocol codecs
There was no measurable difference in test runtime with this, but `timeit` reports a factor 10 speed-up when calling `find_codec_by_name` in a tight loop, so it may make a difference in some cases.
1 parent 491d4fb commit 13887b5

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

multiaddr/codec.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,14 @@
88
from .protocols import read_varint_code
99

1010

11+
CODEC_CACHE = {}
1112
def find_codec_by_name(name):
1213
if not name:
1314
raise ValueError("unknown protocol codec")
14-
return importlib.import_module(".codecs.{0}".format(name), __package__)
15+
codec = CODEC_CACHE.get(name)
16+
if not codec:
17+
codec = CODEC_CACHE[name] = importlib.import_module(".codecs.{0}".format(name), __package__)
18+
return codec
1519

1620

1721
def string_to_bytes(string):

0 commit comments

Comments
 (0)