[Python-checkins] cpython: Optimize tostringlist by taking the stream class outside the function. It's now

eli.bendersky python-checkins at python.org
Tue Jul 17 14:10:20 CEST 2012


http://hg.python.org/cpython/rev/51978f89e5ed
changeset:   78156:51978f89e5ed
user:        Eli Bendersky <eliben at gmail.com>
date:        Tue Jul 17 15:09:12 2012 +0300
summary:
  Optimize tostringlist by taking the stream class outside the function. It's now 2x faster on short calls. Related to #1767933

files:
  Lib/xml/etree/ElementTree.py |  38 +++++++++++++----------
  1 files changed, 22 insertions(+), 16 deletions(-)


diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py
--- a/Lib/xml/etree/ElementTree.py
+++ b/Lib/xml/etree/ElementTree.py
@@ -1184,23 +1184,29 @@
 # @defreturn sequence
 # @since 1.3
 
+class _ListDataStream(io.BufferedIOBase):
+    """ An auxiliary stream accumulating into a list reference
+    """
+    def __init__(self, lst):
+        self.lst = lst
+        
+    def writable(self):
+        return True
+
+    def seekable(self):
+        return True
+
+    def write(self, b):
+        self.lst.append(b)
+
+    def tell(self):
+        return len(self.lst)
+
 def tostringlist(element, encoding=None, method=None):
-    data = []
-    class DataStream(io.BufferedIOBase):
-        def writable(self):
-            return True
-
-        def seekable(self):
-            return True
-
-        def write(self, b):
-            data.append(b)
-
-        def tell(self):
-            return len(data)
-
-    ElementTree(element).write(DataStream(), encoding, method=method)
-    return data
+    lst = []
+    stream = _ListDataStream(lst)
+    ElementTree(element).write(stream, encoding, method=method)
+    return lst
 
 ##
 # Writes an element tree or element structure to sys.stdout.  This

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


More information about the Python-checkins mailing list