arrays methods vs iterator methods (v6)

Revision 6 of this benchmark created on


Description

creating N (50) items, apply trivial calculations and display results (in order make sure no code gets dead-code-eliminated).

Setup

var numbers = Array.from({length: 500}, (v, i) => i)

class NumberMapper {
  constructor(iterable) {
    this.iterable = iterable;
    this.mappingFunctions = [];
  }

  map(mapperFn) {
    this.mappingFunctions.push(mapperFn);
    return this;
  }

  *[Symbol.iterator]() {
    for (const item of this.iterable) {
      let result = item;
      for (const mapperFn of this.mappingFunctions) {
        result = mapperFn(result);
      }
      yield result;
    }
  }

  forEach(callback) {
    for (const item of this) {
      callback(item);
    }
  }
}

Test runner

Ready to run.

Testing in
TestOps/sec
array methods
numbers = new Array(500).fill(1);

numbers
  .map(x => x+1)
  .map(x => x*2)
  .map(x => x-1)
  .map(x => x/2)
  .forEach(x => console.log(x))
ready
iterators
numbers = new Array(500).fill(1);

function * map(mapperFn, iterable){
  for (const item of iterable){
  	yield mapperFn(item)
  }	
}
numbers = map(x => x+1, numbers)
numbers = map(x => x*2, numbers)
numbers = map(x => x-1, numbers)
numbers = map(x => x/2, numbers)
for (const item of numbers){
	console.log(item)
}	
ready
Iterable
numbers = new Array(500).fill(1);

const numberMapper = new NumberMapper(numbers);

numberMapper
  .map((x) => x + 1)
  .map((x) => x * 2)
  .map((x) => x - 1)
  .map((x) => x / 2)
  .forEach((x) => console.log(x));
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.