views:

156

answers:

3

I posted a question yesterday dealing with parsing json data. In one of the follow up answers someone said I was taking a performance hit by using the jQuery append() function within each iteration, while using each().

I was doing:

$.getJSON("http://myurl.com/json?callback=?", 
  function(data) {        

  // loop through each post 
  $.each(data.posts, function(i,posts){ 

    ... parsing ...

    // append
    $('ul').append('<li>...</li>');

  }); 

 });

I modified it to be this:

$.getJSON("http://myurl.com/json?callback=?", 
  function(data) { 

     // create array
     arrPosts = new Array(); 

      // loop through each post
      $.each(data.posts, function(i,posts){ 

       ... parsing ...

        arrPosts[i] = '<li> ... </li>'; 

      });           

      // output
      for (i=0;i<arrPosts.length;i++){ 
        $('ul').append(arrPosts[i]); 
      } 

  });

And this seems to be working properly, example demo: http://jsbin.com/isuro

But am I doing this right? I'm somewhat of a noob and just want to make sure I'm approaching this correctly. Thanks for any advice!

A: 

you shouldn't have to iterate to output.

$('ul').append( arrPosts.join( "\n" ) );

Otherwise looks fine

Peter Bailey
Works perfectly. I obviously need to read up on working with javascript arrays. ;-)
jyoseph
+1  A: 

You are still doing it wrong. The point is you don't want to modify DOM in a loop, because it's just so slow. You were adding items to an array so then you can just add all of them in one function call:

$('ul').append(arrPosts.join(''));
RaYell
+1  A: 

In most browsers it will be quicker to append one large HTML string than to perform multiple small appends. Thus

 $('ul').append( arrPosts.join( "\n" ) );

Should yield better results than

  for (i=0;i<arrPosts.length;i++){ 
    $('ul').append(arrPosts[i]); 
  }

(Obviously, this difference is significant only if you are adding a large number of elements)

Itay