Static local variables

joe joeedh at
Mon Aug 10 16:16:28 UTC 2015

I've been hesitant to bring up this idea, because even though I use it
extensively as a language extension in my transpiler I'm not sure it is
normatively correct.

When I started my first major JS project four or five years ago, I noticed
I was doing this a lot:

    var intersect_vector_tmp = new Vector();

    function intersect_vector(v1, v2) {
        var tmp = intersect_vector_tmp .load(v1).sub(v2);
        //do something

Basically, I was doing the following transform:

*  For each static local variable...
    1. Build unique name from hash of lexical scope chain
    2. Rename variable (along with references to it in the local hoisted
    3. Move it to module/global namespace.

I ended up implemented this in my compiler as a sort of C-style static
local variable.  Thus, the example above became:

    function intersect_vector(v1, v2) {

        static tmp = new Vector();

        //do something

There are, obviously, a great many problems here, starting with the fact
that the variable's initializers are being evaluated outside of the scope
they were declared in.  Unfortunately this pattern can be hard to avoid for
high-performance code, so much so that if the transformation is done by
hand you end up with a great deal of clutter.  This is especially annoying
when dealing with classes, as the following file (with the statics
transpiled out) illustrates:

This becomes a real pain after a while.  At one point I tried using shared
object pools, but found that this didn't remove very much clutter because,
in practice, each function had to have its own pool (usually one for each
type of temporary object it uses).  This really does boil down to a lack of
support for local stack allocation of temporary objects.

Anyway, I just thought I'd put this out there. Who knows, maybe someone
will invent perfect escape analysis for temporary const objects, and we
won't need hackish language extensions such as this.

What do people think? Too many normative problems?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list