Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 31faeaa

Browse files
IgorMinarrodyhaddad
authored andcommitted
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.
1 parent e35abc9 commit 31faeaa

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

src/jqLite.js

+19-5
Original file line numberDiff line numberDiff line change
@@ -370,17 +370,31 @@ function jqLiteAddClass(element, cssClasses) {
370370
}
371371
}
372372

373+
373374
function jqLiteAddNodes(root, elements) {
375+
// THIS CODE IS VERY HOT. Don't make changes without benchmarking.
376+
374377
if (elements) {
375-
elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
376-
? elements
377-
: [ elements ];
378-
for(var i=0; i < elements.length; i++) {
379-
root.push(elements[i]);
378+
379+
// if a Node (the most common case)
380+
if (elements.nodeType) {
381+
root[root.length++] = elements;
382+
} else {
383+
var length = elements.length;
384+
385+
// if an Array or NodeList and not a Window
386+
if (typeof length === 'number' && elements.window !== elements) {
387+
if (length) {
388+
push.apply(root, elements);
389+
}
390+
} else {
391+
root[root.length++] = elements;
392+
}
380393
}
381394
}
382395
}
383396

397+
384398
function jqLiteController(element, name) {
385399
return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
386400
}

test/jqLiteSpec.js

+2
Original file line numberDiff line numberDiff line change
@@ -963,6 +963,8 @@ describe('jqLite', function() {
963963
},
964964
detachEvent: noop
965965
};
966+
window.window = window;
967+
966968
var log;
967969
var jWindow = jqLite(window).on('hashchange', function() {
968970
log = 'works!';

0 commit comments

Comments
 (0)