From: Raymond Hettinger Date: Sun, 18 May 2014 20:02:25 +0000 (+0100) Subject: Don't grow strings by concatenation. Use ''.join() instead. X-Git-Tag: v3.4.2rc1~523^2 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=ae4bab71e3937aaa866d297862a4572e704ab880;p=thirdparty%2FPython%2Fcpython.git Don't grow strings by concatenation. Use ''.join() instead. --- diff --git a/Doc/howto/sockets.rst b/Doc/howto/sockets.rst index 7a9b0edc1944..820beb5cff2d 100644 --- a/Doc/howto/sockets.rst +++ b/Doc/howto/sockets.rst @@ -204,13 +204,15 @@ length message:: totalsent = totalsent + sent def myreceive(self): - msg = b'' - while len(msg) < MSGLEN: - chunk = self.sock.recv(MSGLEN-len(msg)) + chunks = [] + bytes_recd = 0 + while bytes_recd < MSGLEN: + chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048)) if chunk == b'': raise RuntimeError("socket connection broken") - msg = msg + chunk - return msg + chucks.append(chunk) + bytes_recd = bytes_recd + len(chunk) + return b''.join(chunks) The sending code here is usable for almost any messaging scheme - in Python you send strings, and you can use ``len()`` to determine its length (even if it has