From e4c7e9f27877ac36c44e88cf62b70ffa2cbfb2da Mon Sep 17 00:00:00 2001
From: Stefan Behnel <stefan_ml@behnel.de>
Date: Mon, 21 Mar 2016 18:29:40 +0100
Subject: [PATCH] avoid formatting call overhead for simple Unicode value case

---
 Cython/Compiler/ExprNodes.py     | 9 ++++++++-
 Cython/Utility/ModuleSetupCode.c | 1 +
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py
index e037a0cd3..ba0a6dc38 100644
--- a/Cython/Compiler/ExprNodes.py
+++ b/Cython/Compiler/ExprNodes.py
@@ -3024,8 +3024,15 @@ class FormattedValueNode(ExprNode):
             ))
             code.put_gotref(conversion_result)
 
-        code.put("%s = PyObject_Format(%s, %s); " % (
+        if isinstance(self.format_spec, UnicodeNode) and not self.format_spec.value:
+            # common case: no format spec => expect Unicode pass-through
+            format_func = '__Pyx_PyObject_FormatSimple'
+        else:
+            format_func = 'PyObject_Format'
+
+        code.put("%s = %s(%s, %s); " % (
             self.result(),
+            format_func,
             conversion_result,
             self.format_spec.py_result()))
 
diff --git a/Cython/Utility/ModuleSetupCode.c b/Cython/Utility/ModuleSetupCode.c
index a5576cef2..28728384c 100644
--- a/Cython/Utility/ModuleSetupCode.c
+++ b/Cython/Utility/ModuleSetupCode.c
@@ -123,6 +123,7 @@
   #define PyObject_Realloc(p)  PyMem_Realloc(p)
 #endif
 
+#define __Pyx_PyObject_FormatSimple(s, f) (likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) : PyObject_Format(s, f))
 #define __Pyx_PyString_FormatSafe(a, b)   ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b))
 #define __Pyx_PyUnicode_FormatSafe(a, b)  ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b))
 
-- 
2.30.9