Skip to content

Use IIFE for function/method/class definition #2626

@denis-migdal

Description

@denis-migdal

Currently, Brython defines functions as :

function foo288943(){
      var locals
      var locals_exec_foo = locals = {};
      if(arguments.length !== 0){
        foo288943.$args_parser(foo288943, arguments)
      }
      var frame = ["foo", locals, "exec", locals_exec, foo288943]
      $B.enter_frame(frame, __file__, 1)
      try{
        $B.js_this = this
        $B.set_lineno(frame, 2)
        void(0)
        return $B.trace_return_and_leave(frame, _b_.None)
      }catch(err){
        $B.set_exc_and_leave(frame, err)
      }
    }
    foo288943.$function_infos = ['exec', 'foo', 'foo', __file__, _b_.None, _b_.None, _b_.None, [], null, null,
    0, 1, 3, [], 0, 0, [], false, []]
    foo288943.$args_parser = $B.make_args_parser_and_parse
    foo288943.__annotate__ = _b_.None
    locals_exec.foo = foo288943

I think this can be slightly improved by using the IIFE pattern:

locals_exec.foo = (() => {
     function foo() {
         // foo() impl.
     }
     // do some init.
     return foo;
})();

JS engine would immediately inline such function call, so it shouldn't have any cost. However it'd have several advantages:

  • you'll be able to have a local context, so won't leak any temporary variables used for the function definition (if needed).
  • it will be easier to see where the function definition ends.

TBF I find function definitions quite long, and it would be great to have something like:

local_exec.foo  = $B.createFunction(
       {...}, // function meta-data used to create the function.
       () => {
             void(0)
             return $B.trace_return_and_leave(frame, _b_.None)
       }
);

Call performances should remain identical as I assume JS engines are clever enough to inline the callback.
Function creation may be a little slower... though on the other hand we'll also gain time:

  • for JS code generation (as well as JS code storing operations) ;
  • for JS code parsing by the browser (which is hard to measure but can be quite slow).

Dunno if it is something worth exploring.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions