]> granicus.if.org Git - python/commitdiff
Close #16757: Avoid calling the expensive _PyUnicode_FindMaxChar() function
authorVictor Stinner <victor.stinner@gmail.com>
Wed, 3 Apr 2013 00:02:33 +0000 (02:02 +0200)
committerVictor Stinner <victor.stinner@gmail.com>
Wed, 3 Apr 2013 00:02:33 +0000 (02:02 +0200)
when possible

Objects/unicodeobject.c
Python/formatter_unicode.c

index a926e371b1a52de2fa5e1fa62a396937f557b93b..dee2953017a0c47239fb2dc54475c19e59e794cf 100644 (file)
@@ -13777,7 +13777,7 @@ unicode_format_arg_output(struct unicode_formatter_t *ctx,
     Py_ssize_t pindex;
     Py_UCS4 signchar;
     Py_ssize_t buflen;
-    Py_UCS4 maxchar, bufmaxchar;
+    Py_UCS4 maxchar;
     Py_ssize_t sublen;
     _PyUnicodeWriter *writer = &ctx->writer;
     Py_UCS4 fill;
@@ -13830,23 +13830,26 @@ unicode_format_arg_output(struct unicode_formatter_t *ctx,
         arg->width = len;
 
     /* Prepare the writer */
-    bufmaxchar = 127;
+    maxchar = writer->maxchar;
     if (!(arg->flags & F_LJUST)) {
         if (arg->sign) {
             if ((arg->width-1) > len)
-                bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
+                maxchar = MAX_MAXCHAR(maxchar, fill);
         }
         else {
             if (arg->width > len)
-                bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
+                maxchar = MAX_MAXCHAR(maxchar, fill);
         }
     }
-    maxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
-    bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
+    if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
+        Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
+        maxchar = MAX_MAXCHAR(maxchar, strmaxchar);
+    }
+
     buflen = arg->width;
     if (arg->sign && len == arg->width)
         buflen++;
-    if (_PyUnicodeWriter_Prepare(writer, buflen, bufmaxchar) == -1)
+    if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
         return -1;
 
     /* Write the sign if needed */
index 79fa4696977dc065dbd614cca5a3e8752ee592f8..009bc5fd03605d7efbd91c569e73fd67e8bd6f24 100644 (file)
@@ -771,9 +771,13 @@ format_string_internal(PyObject *value, const InternalFormatSpec *format,
 
     calc_padding(len, format->width, format->align, &lpad, &rpad, &total);
 
-    maxchar = _PyUnicode_FindMaxChar(value, 0, len);
+    maxchar = writer->maxchar;
     if (lpad != 0 || rpad != 0)
         maxchar = Py_MAX(maxchar, format->fill_char);
+    if (PyUnicode_MAX_CHAR_VALUE(value) > maxchar) {
+        Py_UCS4 valmaxchar = _PyUnicode_FindMaxChar(value, 0, len);
+        maxchar = Py_MAX(maxchar, valmaxchar);
+    }
 
     /* allocate the resulting string */
     if (_PyUnicodeWriter_Prepare(writer, total, maxchar) == -1)