From e429763dea5a64883b9c133346df6bad6c819558 Mon Sep 17 00:00:00 2001 From: Rapptz Date: Wed, 6 Feb 2019 02:11:44 -0500 Subject: [PATCH] Try to optimize for the common ASCII case. This is still a slowdown (about 45ns to 300ns) but it's less severe than the original implementation (about 900 to 1100ns). --- discord/utils.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/discord/utils.py b/discord/utils.py index b581607bc..d60ca9954 100644 --- a/discord/utils.py +++ b/discord/utils.py @@ -40,7 +40,6 @@ import warnings from .errors import InvalidArgument DISCORD_EPOCH = 1420070400000 -UNICODE_WIDE_CHAR_TYPE = u"WFA" class cached_property: def __init__(self, function): @@ -327,9 +326,17 @@ class SnowflakeList(array.array): i = bisect_left(self, element) return i != len(self) and self[i] == element -def _string_width(string): +_IS_ASCII = re.compile(r'^[\x00-\x7f]+$') + +def _string_width(string, *, _IS_ASCII=_IS_ASCII): """Returns string's width.""" + match = _IS_ASCII.match(string) + if match: + return match.endpos + + UNICODE_WIDE_CHAR_TYPE = 'WFA' width = 0 + func = unicodedata.east_asian_width for char in string: - width += 2 if unicodedata.east_asian_width(char) in UNICODE_WIDE_CHAR_TYPE else 1 + width += 2 if func(char) in UNICODE_WIDE_CHAR_TYPE else 1 return width