Skip to content

Instantly share code, notes, and snippets.

@justdoit0823
Created December 28, 2018 12:09
Show Gist options
  • Save justdoit0823/b40a78e7a92a64428d8fed5e4829d4ea to your computer and use it in GitHub Desktop.
Save justdoit0823/b40a78e7a92a64428d8fed5e4829d4ea to your computer and use it in GitHub Desktop.
Compare `str` function and format string in Python 3.7
  • Benchmark result
root@localhost:~# python3.7 -m timeit -s 'x = 6' 'f"{x}"'
5000000 loops, best of 5: 79 nsec per loop
root@localhost:~# python3.7 -m timeit -s 'x = 6' 'str(x)'
1000000 loops, best of 5: 214 nsec per loop
  • Code snippet
def foo(x):
  str(x)

def bar(x):
  f"{x}"
  • Bytecode
  2           0 LOAD_GLOBAL              0 (str)
              2 LOAD_FAST                0 (x)
              4 CALL_FUNCTION            1
              6 POP_TOP
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
             
  2           0 LOAD_FAST                0 (f)
              2 FORMAT_VALUE             0
              4 POP_TOP
              6 LOAD_CONST               0 (None)
              8 RETURN_VALUE
  • CPython
/* Fast path for common types. */
if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
    if (PyUnicode_CheckExact(obj)) {
        Py_INCREF(obj);
        return obj;
    }
    if (PyLong_CheckExact(obj)) {
        return PyObject_Str(obj);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment