[Lxml-checkins] r52347 - in lxml/trunk: . src/lxml

scoder at codespeak.net scoder at codespeak.net
Sun Mar 9 17:53:09 CET 2008


Author: scoder
Date: Sun Mar  9 17:53:08 2008
New Revision: 52347

Modified:
   lxml/trunk/   (props changed)
   lxml/trunk/src/lxml/lxml.etree.pyx
Log:
 r3749 at delle:  sbehnel | 2008-03-09 12:12:23 +0100
 reuse namespace prefixes instead of building them on each request


Modified: lxml/trunk/src/lxml/lxml.etree.pyx
==============================================================================
--- lxml/trunk/src/lxml/lxml.etree.pyx	(original)
+++ lxml/trunk/src/lxml/lxml.etree.pyx	Sun Mar  9 17:53:08 2008
@@ -330,7 +330,11 @@
         return (version, encoding)
 
     cdef buildNewPrefix(self):
-        ns = python.PyString_FromFormat("ns%d", self._ns_counter)
+        if self._ns_counter < python.PyTuple_GET_SIZE(_PREFIX_CACHE):
+            ns = python.PyTuple_GET_ITEM(_PREFIX_CACHE, self._ns_counter)
+            python.Py_INCREF(ns)
+        else:
+            ns = python.PyString_FromFormat("ns%d", self._ns_counter)
         if self._prefix_tail is not None:
             ns += self._prefix_tail
         self._ns_counter += 1
@@ -364,17 +368,15 @@
             dict_result = python.PyDict_GetItemString(
                 _DEFAULT_NAMESPACE_PREFIXES, c_href)
             if dict_result is not NULL:
-                c_prefix = _cstr(<object>dict_result)
-
-        if c_prefix is NULL or \
-               tree.xmlSearchNs(self._c_doc, c_node, c_prefix) is not NULL:
-            # try to simulate ElementTree's namespace prefix creation
-            while 1:
+                prefix = <object>dict_result
+            else:
                 prefix = self.buildNewPrefix()
-                c_prefix = _cstr(prefix)
-                # make sure it's not used already
-                if tree.xmlSearchNs(self._c_doc, c_node, c_prefix) is NULL:
-                    break
+            c_prefix = _cstr(prefix)
+
+        # make sure the prefix is not in use already
+        while tree.xmlSearchNs(self._c_doc, c_node, c_prefix) is not NULL:
+            prefix = self.buildNewPrefix()
+            c_prefix = _cstr(prefix)
 
         c_ns = tree.xmlNewNs(c_node, c_href, c_prefix)
         if c_ns is NULL:
@@ -424,6 +426,14 @@
             self._setNodeNs(c_node, _cstr(node_ns_utf))
         return 0
 
+cdef __initPrefixCache():
+    cdef int i
+    return tuple([ python.PyString_FromFormat("ns%d", i)
+                   for i from 0 <= i < 30 ])
+
+cdef object _PREFIX_CACHE
+_PREFIX_CACHE = __initPrefixCache()
+
 cdef extern from "etree_defs.h":
     # macro call to 't->tp_new()' for fast instantiation
     cdef _Document NEW_DOCUMENT "PY_NEW" (object t)


More information about the lxml-checkins mailing list