--
For other discussions, see https://groups.google.com/a/dartlang.org/
For HOWTO questions, visit http://stackoverflow.com/tags/dart
To file a bug report or feature request, go to http://www.dartbug.com/new
To unsubscribe from this group and stop receiving emails from it, send an email to misc+uns...@dartlang.org.
- Foreach() loops are about 2x slower than using a for(var i...) loop
const trials = 10;const iterations = 10000000;void time(String name, benchmark()) {var start = new DateTime.now();for (var i = 0; i < trials; i++) {benchmark();}var elapsed = new DateTime.now().difference(start).inMilliseconds / trials;print("$name: $elapsed ms/trial");}void main() {var list = [];for (var i = 0; i< iterations; i++){list.add(i);}time("forEach()", () {var sum = 0;list.forEach((i) {sum += i;});if (sum == 1000) print("prevent dead code elimination");});time("for()", () {var sum = 0;for (var i = 0; i < list.length; i++) {sum += i;}if (sum == 1000) print("prevent dead code elimination");});time("while()", () {var sum = 0;var iterator = list.iterator;while (iterator.moveNext()) {sum += iterator.current;}if (sum == 1000) print("prevent dead code elimination");});}
forEach(): 46.5 ms/trialfor(): 6.6 ms/trialwhile(): 15.7 ms/trial
sum += list[i];
For a fair comparison? Currently foreach and while perform list access, while for does not.
On my machine this only adds 3ms to the for loop time, so the overall conclusion remains the same. Though for some reason my while speeds are much closer to the foreach speeds than yours are:
foreach(): 52.6 ms/trial
for(): 9.6 ms/trial
while(): 43.1 ms/trial
sum += list[i];
--
NoOperatorOverloading: { "^": "BenchmarkBase;myClazzes,myClazz,name,emitter", setup$0: function() { var t1, i; for (t1 = this.myClazzes, i = 0; i < 100000; ++i) t1.push(new N.Clazz(i)); }, run$0: function() { var t1, t2, i, t3; for (t1 = this.myClazzes, t2 = this.myClazz, i = 0; i < t1.length; ++i) { t3 = t1[i]; t2.myInteger = t2.myInteger + t3.myInteger; } }, teardown$0: function() { } }, OperatorOverloading: { "^": "BenchmarkBase;myClazzes,myClazz,name,emitter", setup$0: function() { var t1, i; for (t1 = this.myClazzes, i = 0; i < 100000; ++i) t1.push(new N.Clazz(i)); }, run$0: function() { var t1, t2, i, t3; for (t1 = this.myClazzes, t2 = this.myClazz, i = 0; i < t1.length; ++i) { t3 = t1[i]; t2.myInteger = t2.myInteger + t3.myInteger; } }, teardown$0: function() { } },