gkz / LiveScript

LiveScript is a language which compiles to JavaScript. It has a straightforward mapping to JavaScript and allows you to write expressive code devoid of repetitive boilerplate. While LiveScript adds many features to assist in functional style programming, it also has many improvements for object oriented and imperative programming.
http://livescript.net
MIT License
2.31k stars 156 forks source link

Force creation of a function in a loop? (unwanted optimiziation) #1079

Open determin1st opened 5 years ago

determin1st commented 5 years ago

Hi there, I was assembling constructor functions in a map with similar code:

# create constructors map
map = new !->
  for a of type
    # create constructor
    @[a] = b = !->
      @prop1 = false
      @prop2 = false
    # set its prototype (methods)
    b.prototype = type[a]

the output:

map = new function(){
  var a, b;
  for (a in type) {
    this[a] = b = fn$;
    b.prototype = type[a];
  }
  function fn$(){
    this.prop1 = false;
    this.prop2 = false;
  }
};

Is there a way to force creation (not definition) logic?

rhendric commented 5 years ago

Huh. That looks like a bug to me, or at the very least a completely undocumented gotcha.

I can think of two workarounds, at least: change for a to for let a, or change b = !-> to b = do -> !->. Both add some overhead at run time, which is unfortunate, but it might be mostly optimized out by a JS engine.

determin1st commented 5 years ago

ye, okay, i've created some factory function outside of the loop for now.. the construction overhead doesn't matter much in my case (it's a singleton object), it just doesn't look "good enough".

determin1st commented 5 years ago

well, i've got some answer from the JIT-man:

"Different constructor functions will have different hidden classes"

So my intent to make some set of "look-alike" constructors with the same hidden class won't work with this pattern. Maybe, it's not a bug, i see no reason to write such code constructs now..

ceremcem commented 5 years ago

Looks like very same issue: https://stackoverflow.com/a/41587540/1952991

determin1st commented 5 years ago

@ceremcem yes yes, it's the same.. almost.

ceremcem commented 2 years ago

Any update on this issue?

rhendric commented 2 years ago

Nobody's working on LiveScript in secret. What you see is what you get.

ceremcem commented 2 years ago

Would you accept a patch that entirely removes that optimization?

rhendric commented 2 years ago

Short answer, I don't know if that's a good idea. It's been a few years since I've dug into LiveScript. If you've done the research and can make a logical case that the optimization doesn't help, I'd look at it. Given LiveScript's status as a legacy language I don't want to remove anything that some project might be relying on.