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

Better inlining of for-loops with anonymous iterators. #8848

Merged

Conversation

RealyUniqueName
Copy link
Member

This PR allows to inline for loops with Iterator or Iterable provided as type parameter without allocating an iterator.
Here is an example:

Main.hx
class Main {
  public static function main() {
      iter(new Collection(10));
  }

  static public inline function iter<A,T:Iterable<A>>(v:T) {
      for(i in v) {
          trace(i);
      }
  }
}

class Collection<V> {
  public var amount:Int;
  public inline function new(amount:Int) this.amount = amount;
  public inline function iterator() return new CollectionIterator(this);
}

class CollectionIterator<V> {
  var collection:Collection<V>;
  var current:Int = 0;
  public inline function new(collection:Collection<V>) this.collection = collection;
  public inline function hasNext() return current++ < collection.amount;
  public inline function next() return (null:V);

}
JS compiled _with_ this PR
// Generated by Haxe 4.0.0-rc.5
(function ($global) { "use strict";
var Main = function() { };
Main.main = function() {
    var _g_collection_amount = 10;
    var _g_current = 0;
    while(_g_current++ < _g_collection_amount) {
        var i = null;
        console.log("src/Main.hx:8:",i);
    }
};
Main.main();
})({});
JS compiled _without_ this PR
// Generated by Haxe 4.0.0-rc.5
(function ($global) { "use strict";
var Main = function() { };
Main.main = function() {
    var i = new CollectionIterator(new Collection(10));
    while(i.hasNext()) {
        var i1 = i.next();
        console.log("src/Main.hx:8:",i1);
    }
};
var Collection = function(amount) {
    this.amount = amount;
};
Collection.prototype = {
    iterator: function() {
        return new CollectionIterator(this);
    }
};
var CollectionIterator = function(collection) {
    this.current = 0;
    this.collection = collection;
};
CollectionIterator.prototype = {
    hasNext: function() {
        return this.current++ < this.collection.amount;
    }
    ,next: function() {
        return null;
    }
};
Main.main();
})({});

If this PR is accepted I'll make another one which will make Lambda methods allocation-free

@RealyUniqueName RealyUniqueName added this to the Release 4.1 milestone Sep 25, 2019
@skial skial mentioned this pull request Sep 26, 2019
1 task
@Simn Simn merged commit 527ebe9 into HaxeFoundation:development Nov 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants