def ensure_bytes__try(data):
try:
# memoryview used only for testing type; 'with' releases the view instantly
with memoryview(data):
return data
except TypeError:
return data.encode()
def ensure_bytes__isinstance(data):
# Explicitly test for some bytes-like types
# - misses array.array, numpy.array and all other types not listed here
return data if isinstance(data, (bytes, bytearray, memoryview)) else data.encode()
def ensure_bytes__hasattr(data):
# Works as long as your bytes-like doesn't have 'encode'
return data.encode() if hasattr(data, "encode") else data
def ensure_bytes__args(data=None, data_bytes=None):
# Avoid autodetection by using explicit arguments
return data_bytes if data is None else data.encode()
# New-style buffer API, for Python 2.7 and 3.x.
# PyObject_CheckBuffer uses the new-style API.
# 2.6 also has the new-style API, but no memoryview,
# so you can't use it or check compatibility from Python code.
try:
memoryview(thing)
except TypeError:
# Doesn't support it!
# Old-style API. Doesn't exist in 3.x.
# Not quite equivalent to PyObject_CheckBuffer.
try:
buffer(thing)
except TypeError:
# Doesn't support it!
在处理性能关键代码的简短数据片段时,我不得不尝试不同的方法。根据您的应用程序,其中一个可能比其他更好。在
以下基准测试显示了Python 3.7.4上的每个实现所使用的时间:
^{pr2}$短条意味着更快。每个条的浅色部分表示以
ref_bytes(b"foo")
(84 ns)和ref_str("foo")
(100 ns)为基准的参考时间:我认为你应该使用标准的方法,试试看它是否有效:
相关问题 更多 >
编程相关推荐