From a25e117412522b6b012eeb484ec03c787f97feab Mon Sep 17 00:00:00 2001 From: griffpatch Date: Sat, 28 Jan 2017 14:38:13 +0000 Subject: [PATCH] optimisation/avoid negative index lookups #407 Run-time Optimisation The thread.stackFrames array is accessed all the time to retrieve the 'parent' stack frame. This is done using as index of [this.stack.length - 1]. However, a lot of the time this evaluated to [-1]. Although this results in null, which is fine, to get to this javascript actually defers from a numeric array lookup to an object lookup using the string "-1". This is roughly 100 times slower to compute and so a simple catch for negative indexes is well worth the extra check. --- src/engine/thread.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/engine/thread.js b/src/engine/thread.js index 765f48b71..6402bd4e5 100644 --- a/src/engine/thread.js +++ b/src/engine/thread.js @@ -101,7 +101,6 @@ Thread.prototype.pushStack = function (blockId) { if (this.stack.length > this.stackFrames.length) { // Copy warp mode from any higher level. var warpMode = false; - if (this.stackFrames[this.stackFrames.length - 1]) { warpMode = this.stackFrames[this.stackFrames.length - 1].warpMode; } this.stackFrames.push({ @@ -129,7 +128,7 @@ Thread.prototype.popStack = function () { * @return {?string} Block ID on top of stack. */ Thread.prototype.peekStack = function () { - return this.stack[this.stack.length - 1]; + return this.stack.length > 0 ? this.stack[this.stack.length - 1] : null; }; @@ -138,7 +137,7 @@ Thread.prototype.peekStack = function () { * @return {?Object} Last stack frame stored on this thread. */ Thread.prototype.peekStackFrame = function () { - return this.stackFrames[this.stackFrames.length - 1]; + return this.stackFrames.length > 0 ? this.stackFrames[this.stackFrames.length - 1] : null; }; /** @@ -146,7 +145,7 @@ Thread.prototype.peekStackFrame = function () { * @return {?Object} Second to last stack frame stored on this thread. */ Thread.prototype.peekParentStackFrame = function () { - return this.stackFrames[this.stackFrames.length - 2]; + return this.stackFrames.length > 1 ? this.stackFrames[this.stackFrames.length - 2] : null; }; /**