From 19eaa181a524f9a1ed9f4073f284a5dde271a6d0 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Wed, 14 Jan 2015 20:02:40 +0300 Subject: [PATCH] Speed up common case where consumer moves only forward --- lib/6to5/generation/whitespace.js | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/6to5/generation/whitespace.js b/lib/6to5/generation/whitespace.js index 6d16536f26..5e356c2f27 100644 --- a/lib/6to5/generation/whitespace.js +++ b/lib/6to5/generation/whitespace.js @@ -3,9 +3,22 @@ module.exports = Whitespace; var _ = require("lodash"); var util = require("../util"); +// a helper to iterate array from arbitrary index +function getLookupIndex(i, base, max) { + i += base; + + if (i >= max) + i -= max; + + return i; +} + function Whitespace(tokens, comments) { this.tokens = _.sortBy(tokens.concat(comments), "start"); this.used = []; + + // speed up common case where methods are called for next tokens + this._lastFoundIndex = 0; } Whitespace.prototype.getNewlinesBefore = function (node) { @@ -14,13 +27,15 @@ Whitespace.prototype.getNewlinesBefore = function (node) { var tokens = this.tokens; var token; - for (var i = 0; i < tokens.length; i++) { + for (var j = 0; j < tokens.length; j++) { + var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length); token = tokens[i]; // this is the token this node starts with if (node.start === token.start) { startToken = tokens[i - 1]; endToken = token; + this._lastFoundIndex = i; break; } } @@ -34,13 +49,15 @@ Whitespace.prototype.getNewlinesAfter = function (node) { var tokens = this.tokens; var token; - for (var i = 0; i < tokens.length; i++) { + for (var j = 0; j < tokens.length; j++) { + var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length); token = tokens[i]; // this is the token this node ends with if (node.end === token.end) { startToken = token; endToken = tokens[i + 1]; + this._lastFoundIndex = i; break; } }