0

I was wondering whether using bytearray for constructing a string like.

def build_string(pairs):
    data = ''
    for key, value in pairs.iteritems():
        data = data + '\r\n' + '%s:%s' % (key, value)
    data = data + '\r\n\r\n'
    return data

would be slower than.

def build_string(pairs):
    data = bytearray()
    for key, value in pairs.iteritems():
        data.extend('%s:%s\r\n' % (key, value))
    data.extend('\r\n')
    return data

1 Answer 1

6

You should just use str.join()

You generally shouldn't need to include the carriage return (\r). Python has universal newline support. It will use the correct line ending for the OS.

return '\n'.join('{0}:{1}'.format(k, v) for k, v in pairs.iteritems()) + '\n\n'
Sign up to request clarification or add additional context in comments.

2 Comments

i have used this code. codepad.org/zvHgPP0f it seems test2 is faster than both test1 and test3
@tau Only for short lists and short strings. Make the list longer, or use longer key and value strings and it gets exponentially worse. The bytearray version can actually be a bit faster, but it depends on whether you want to support non-ascii or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.