Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add BUILD_STRING opcode to optimize string interpolation (like python) #182

Open
ThakeeNathees opened this issue Apr 6, 2022 · 0 comments
Labels
enhancement Improvements or additions to the source performance Performance related

Comments

@ThakeeNathees
Copy link
Owner

https://bugs.python.org/issue27078

I benchmarked some f'' strings against .format, and surprisingly f'' was slower
than .format in about all the simple cases I could think of. I guess this is
because f'' strings implicitly use `''.join([])`.

The byte code for f'foo is {foo}' currently is

  1           0 LOAD_CONST               1 ('')
              3 LOAD_ATTR                0 (join)
              6 LOAD_CONST               2 ('foo is ')
              9 LOAD_GLOBAL              1 (foo)
             12 FORMAT_VALUE             0
             15 BUILD_LIST               2
             18 CALL_FUNCTION            1 (1 positional, 0 keyword pair)

It was mentioned here https://bugs.python.org/issue24965 but since I came up
with the idea when inspecting this, I'd propose again here that a new opcode
be added for f'' strings - BUILD_STRING n, with which f'foo is {foo}' could
be compiled to 

              0 LOAD_CONST               2 ('foo is ')
              3 LOAD_GLOBAL              1 (foo)
              6 FORMAT_VALUE             0
              9 BUILD_STRING             2

Python 3.7.4

>>> def foo(name):
...     return f"hello {name}"
...
>>> from dis import dis
>>> dis(foo)
  2           0 LOAD_CONST               1 ('hello ')
              2 LOAD_FAST                0 (name)
              4 FORMAT_VALUE             0
              6 BUILD_STRING             2
              8 RETURN_VALUE

Pocketlang (current)

>>> def foo(name)
...     return "hello $name"
... end
>>> from lang import disas
>>> print(disas(foo))
Instruction Dump of function 'foo' "$(REPL)"
     2:     0  PUSH_BUILTIN_FN    14 [Fn:list_join]
            2  PUSH_LIST           2
            5  PUSH_CONSTANT       1 "hello "
            8  LIST_APPEND
            9  PUSH_LOCAL_0          (param:0)
           10  LIST_APPEND
           11  CALL                1 (argc)
           13  RETURN
     3:    14  POP
           15  RETURN
           16  END
@ThakeeNathees ThakeeNathees added enhancement Improvements or additions to the source performance Performance related labels Apr 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Improvements or additions to the source performance Performance related
Projects
None yet
Development

No branches or pull requests

1 participant