Eric V. Smith added the comment:

The good news is that the performance is pretty good, and finally I have a case 
where I can beat %-formatting:

$ ./python.bat -mtimeit -s 'a=2' "'%s' % a"
1000000 loops, best of 3: 0.883 usec per loop

$ ./python.bat -mtimeit -s 'a=2' '"{}".format(a)'
1000000 loops, best of 3: 1.16 usec per loop

$ ./python.bat -mtimeit -s 'a=2' 'f"{a}"'
1000000 loops, best of 3: 0.792 usec per loop

This example is mildly contrived, and the performance of f-strings is slightly 
worse than %-formatting once the f-strings contains both expressions and 
literals.

I could speed it up significantly (I think) by adding opcodes for 2 things: 
calling __format__ and joining the strings together. Calling __format__ in an 
opcode could be a win because I could optimize for known types (str, int, 
float). Having a join opcode would be a win because I could use 
_PyUnicodeWriter instead of ''.join.

I'm inclined to check this code in as-is, then optimize it later, if we think 
it's needed and if I get motivated.

For reference, here's the ast and opcodes for f'a={a}':

>>> ast.dump(ast.parse("f'a={a}'"))
"Module(body=[Expr(value=JoinedStr(values=[Str(s='a='), 
FormattedValue(value=Name(id='a', ctx=Load()), conversion=0, 
format_spec=None)]))])"

>>> dis.dis("f'a={a}'")
  1           0 LOAD_CONST               0 ('')
              3 LOAD_ATTR                0 (join)
              6 LOAD_CONST               1 ('a=')
              9 LOAD_NAME                1 (a)
             12 LOAD_ATTR                2 (__format__)
             15 LOAD_CONST               0 ('')
             18 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             21 BUILD_LIST               2
             24 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             27 RETURN_VALUE

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue24965>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to