I have a buffer object in C ++ that inherits from std::vector<char> . I want to convert this buffer to a Python string so that I can send it over the network via Twisted protocol.transport.write.
Two ways I thought to do: (1) creating a string and filling it char with char:
def scpychar(buf, n): s = '' for i in xrange(0, n): s += buf[i] return s
and (2) creating a char array (since I know how big the buffer is), filling it and converting it to a string
def scpyarr(buf, n): a = array.array('c','0'*n) for i in xrange(0, n): a[i] = buf[i] return a.tostring()
I would think that (1) should create a new string object every time s += buf[i] called and copy the contents of the old string. Therefore, I expected (2) to be faster (1). But if I test this with timeit, I find that (1) is actually about twice as fast as (2).
I was wondering if anyone can explain why (1) is faster?
Bonus points for an even more efficient way of converting from a std::vector<char> string to a Python string.
Corey source share