From 31faeaa7293716251ed437fa54432bb89d9d48de Mon Sep 17 00:00:00 2001 From: Igor Minar Date: Thu, 5 Jun 2014 05:52:09 -0700 Subject: [PATCH] perf(jqLite): optimize adding nodes to a jqLite collection This code is very hot and in most cases we are wrapping just a single Node so we should optimize for that scenario. --- src/jqLite.js | 24 +++++++++++++++++++----- test/jqLiteSpec.js | 2 ++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/jqLite.js b/src/jqLite.js index 297c4304..00f777e0 100644 --- a/src/jqLite.js +++ b/src/jqLite.js @@ -370,17 +370,31 @@ function jqLiteAddClass(element, cssClasses) { } } + function jqLiteAddNodes(root, elements) { + // THIS CODE IS VERY HOT. Don't make changes without benchmarking. + if (elements) { - elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) - ? elements - : [ elements ]; - for(var i=0; i < elements.length; i++) { - root.push(elements[i]); + + // if a Node (the most common case) + if (elements.nodeType) { + root[root.length++] = elements; + } else { + var length = elements.length; + + // if an Array or NodeList and not a Window + if (typeof length === 'number' && elements.window !== elements) { + if (length) { + push.apply(root, elements); + } + } else { + root[root.length++] = elements; + } } } } + function jqLiteController(element, name) { return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); } diff --git a/test/jqLiteSpec.js b/test/jqLiteSpec.js index f71700e2..291282c5 100644 --- a/test/jqLiteSpec.js +++ b/test/jqLiteSpec.js @@ -963,6 +963,8 @@ describe('jqLite', function() { }, detachEvent: noop }; + window.window = window; + var log; var jWindow = jqLite(window).on('hashchange', function() { log = 'works!';