1

I know how to add two jQueries together using add()

However, for a project I am working on, it has become a performance bottleneck. I fiddled around and came up with an alternative, which gives me the same results at a great performance increase (~60ms versus 1000ms in this fiddle):

http://jsfiddle.net/jedierikb/rkAP4/1/

var t = $("#test");
var tKids = t.children( );
var j = $("#jest");
var jKids = j.children( );

var z,
    zMax = 30000;

var time1 = new Date();
for (z=0; z<zMax; z++)
{
    var opt1 = tKids.add( jKids );
}
var time2 = new Date();

for (z=0; z<zMax; z++)
{
    var i,
        iMax,
        allKids = [];
    for(i = 0, iMax = tKids.length; i < iMax; i++)
    {
        allKids.push( tKids[i] );
    }
    for(i = 0, iMax = jKids.length; i < iMax; i++)
    {
        allKids.push( jKids[i] );
    }
    var opt2 = $( allKids );
}
var time3 = new Date();

console.log( (time2-time1) + " v " + (time3-time2) );​

Note: I do not need the benefits of add such as guaranteed dom-element ordering and removal of duplicates.

I am wondering if there is a way to make this approach cleaner or more compact than all of the iterating I am doing. Or maybe there is a better approach all together.

Community
  • 1
  • 1
jedierikb
  • 12,752
  • 22
  • 95
  • 166
  • You can read this: http://www.scottlogic.co.uk/2010/10/javascript-array-performance/ – A. Wolff Oct 23 '12 at 14:27
  • you can also test your JS performance here: http://jsperf.com/jquery-add-alternative-for-performance – RASG Oct 23 '12 at 14:52

2 Answers2

2

I know you might be trying to stay away from the jQuery API methods for performance reasons, but this is worth a shot:

var t = $('#test').children();
var j = $('#jest').children();
var added = t.get().concat(j.get());

I'm not sure how fast .get() is, but I have a hard time imagining it's slower than iterating over each set of children. Could make a jsperf test...

EDIT

For posterity: http://api.jquery.com/get/

The .get() method grants us access to the DOM nodes underlying each jQuery object.

BLSully
  • 5,929
  • 1
  • 27
  • 43
  • Thank you, did not know about using get(). Only adds around 100ms when iterating 30k times. Not too bad. http://jsfiddle.net/jedierikb/rkAP4/2/ – jedierikb Oct 23 '12 at 14:29
0

You can cut down some loops if mixing the order of 'kids' is allowed

for (z=0; z<zMax; z++)
    {
        var tLen = tKids.length;
        var jLen = jKids.length;
        var maxLen = Math.max(tLen, jLen);
        var allKids = [];
        for(var i = 0; i < maxLen; i++)
        {
            if (i<tLen) allKids.push(tKids[i]);
            if (i<jLen) allKids.push(jKids[i]);
        }
        var opt2 = $( allKids );
    }​
st3inn
  • 1,556
  • 9
  • 17