Message250422
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 |
|
Date |
User |
Action |
Args |
2015-09-10 21:28:46 | eric.smith | set | recipients:
+ eric.smith, barry, python-dev, yselivanov |
2015-09-10 21:28:46 | eric.smith | set | messageid: <1441920526.01.0.267806955266.issue24965@psf.upfronthosting.co.za> |
2015-09-10 21:28:46 | eric.smith | link | issue24965 messages |
2015-09-10 21:28:45 | eric.smith | create | |
|