To be specific, I need to convert an integer, say 9999, to bytes, b'9999'in python 2.6 to python 3.x
In python 2.x I do
b'%s'%n
and 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 tests are set up correctly, this is a heavy punishment in python 3.x.
Is there a way to improve performance to close the gap with 2.6 / 2.7?
Perhaps via cython route?
This is the generator function I'm trying to optimize. It is called again and again when it argsis 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 this way.
b''.join(pack_gen(args))