To be specific I need to convert an integer, say 9999
, into bytes, b'9999'
in python 2.6 up to python 3.x
In python 2.x I do
b'%s'%n
while in python 3.x
('%s'%n).encode()
Performance in python 2.6
>>> from timeit import Timer
>>> Timer('b"%s"%n','n=9999').timeit()
0.24728001750963813
Performance in python 3.2
>>> from timeit import Timer
>>> Timer('("%s"%n).encode()','n=9999').timeit()
0.534475012767416
Assuming my benchmarks are set up correctly, that is an hefty penalty in python 3.x.
Is there a way to improve performance to close the gap with 2.6/2.7?
Maybe via the cython route?
This is the generator function I'm trying to optimize. It is called over and over with args
being a list of strings, bytes or numbers:
def pack_gen(self, args, encoding='utf-8'):
crlf = b'\r\n'
yield ('*%s\r\n'%len(args)).encode(encoding)
for value in args:
if not isinstance(value, bytes):
value = ('%s'%value).encode(encoding)
yield ('$%s\r\n'%len(value)).encode(encoding)
yield value
yield crlf
The function is called in this way
b''.join(pack_gen(args))