Library import is slow due to cache prepopulation
Importing openpyxl takes over 100ms, which is disproportionate to most libraries. While I understand import time isn't really a common priority, it's coming up more as scale-out FaaS becomes popular (in my case, AWS Lambda).
The cause seems to be the prefilling of the column string caches. https://foss.heptapod.net/openpyxl/openpyxl/-/blob/branch/3.1/openpyxl/utils/cell.py?ref_type=heads#L99
The _get_column_letter
function does a lot of repeated work given that it's only called with sequentially increasing indexes.
I'm unsure if the project would prefer an improvement here by making the cache only populate if/when accessed or if the generation code should just be made faster.
Changing to the below decreases the import time by over 80% and seems to produce the same result.
from string import ascii_uppercase
from itertools import product, chain
_COL_STRING_CACHE = {
i: "".join(letters)
for i, letters in enumerate(chain(
# A->Z
ascii_uppercase,
# AA->ZZ
product(ascii_uppercase, repeat=2),
# AAA->ZZZ
product(ascii_uppercase, repeat=3),
), start=1)
}
_STRING_COL_CACHE = {
col: i
for i, col in _COL_STRING_CACHE.items()
}