[Python-checkins] cpython (2.7): Don't grow strings by concatenation. Use ''.join() instead.

raymond.hettinger python-checkins at python.org
Sun May 18 21:04:10 CEST 2014


http://hg.python.org/cpython/rev/ae89498cd66b
changeset:   90754:ae89498cd66b
branch:      2.7
parent:      90747:7caf7401aece
user:        Raymond Hettinger <python at rcn.com>
date:        Sun May 18 20:04:01 2014 +0100
summary:
  Don't grow strings by concatenation.  Use ''.join() instead.

files:
  Doc/howto/sockets.rst |  12 +++++++-----
  1 files changed, 7 insertions(+), 5 deletions(-)


diff --git a/Doc/howto/sockets.rst b/Doc/howto/sockets.rst
--- a/Doc/howto/sockets.rst
+++ b/Doc/howto/sockets.rst
@@ -207,13 +207,15 @@
                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

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list