8000 Optimize ensure_str and ensure_binary. (#331) · benjaminp/six@05c4f51 · GitHub
[go: up one dir, main page]

Skip to content

Commit 05c4f51

Browse files
authored
Optimize ensure_str and ensure_binary. (#331)
We found that large applications that have undergone a 2 -> 3 migration and wound up with a lot of six.ensure_str and six.ensure_binary calls could save 1-2% CPU usage by optimizing these for the common case. Further optimization could be done by replacing them with extension module implementations - assumed out of scope for the pure Python six project itself. Ideally all of these calls and use of six in people's code would be removed after there all need for any Python 2 compatibility is gone. But completing that kind of type cleanup requires a lot of human engineering time. This lowers the ongoing costs in the interim. Contributed by YouTube.
1 parent a5bb7aa commit 05c4f51

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

six.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -890,12 +890,11 @@ def ensure_binary(s, encoding='utf-8', errors='strict'):
890890
- `str` -> encoded to `bytes`
891891
- `bytes` -> `bytes`
892892
"""
893+
if isinstance(s, binary_type):
894+
return s
893895
if isinstance(s, text_type):
894896
return s.encode(encoding, errors)
895-
elif isinstance(s, binary_type):
896-
return s
897-
else:
898-
raise TypeError("not expecting type '%s'" % type(s))
897+
raise TypeError("not expecting type '%s'" % type(s))
899898

900899

901900
def ensure_str(s, encoding='utf-8', errors='strict'):
@@ -909,12 +908,15 @@ def ensure_str(s, encoding='utf-8', errors='strict'):
909908
- `str` -> `str`
910909
- `bytes` -> decoded to `str`
911910
"""
912-
if not isinstance(s, (text_type, binary_type)):
913-
raise TypeError("not expecting type '%s'" % type(s))
911+
# Optimization: Fast return for the common case.
912+
if type(s) is str:
913+
return s
914914
if PY2 and isinstance(s, text_type):
915-
s = s.encode(encoding, errors)
915+
return s.encode(encoding, errors)
916916
elif PY3 and isinstance(s, binary_type):
917-
s = s.decode(encoding, errors)
917+
return s.decode(encoding, errors)
918+
elif not isinstance(s, (text_type, binary_type)):
919+
raise TypeError("not expecting type '%s'" % type(s))
918920
return s
919921

920922

0 commit comments

Comments
 (0)
0