]> granicus.if.org Git - python/commitdiff
Don't grow strings by concatenation. Use ''.join() instead.
authorRaymond Hettinger <python@rcn.com>
Sun, 18 May 2014 19:04:01 +0000 (20:04 +0100)
committerRaymond Hettinger <python@rcn.com>
Sun, 18 May 2014 19:04:01 +0000 (20:04 +0100)
Doc/howto/sockets.rst

index e0083edc51ca6e87b92b02f3fdc4dadaa7860a53..0a7fcf5c0c26d44eb981a359449438381cbac121 100644 (file)
@@ -207,13 +207,15 @@ length message::
                totalsent = totalsent + sent
 
        def myreceive(self):
-           msg = ''
-           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 == '':
                    raise RuntimeError("socket connection broken")
-               msg = msg + chunk
-           return msg
+               chucks.append(chunk)
+               bytes_recd = bytes_recd + len(chunk)
+           return ''.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