Reputation: 519
This might be a basic question, but what's confusing is: Are multiple selectors more preferable than single selectors in jquery? I have the following code.
$('#sample_1').css('border', '1px solid #00ffff');
$('#sample_2').css('border', '1px solid #00ffff');
$('.sample_3').css('border', '1px solid #00ffff');
Whats really the advantage in concatenating these as follows. In one post, its given that it may take time to process the commas and then to merge the results, due to which this concatenated form takes more time. Is that so? Will this really boost the performance or is this preferable for code simplicity?
$('#sample_1, #sample_2, .sample_3').css('border', '1px solid #00ffff');
Upvotes: 0
Views: 53
Reputation: 74
I think with this particular usecase, where you're thinking that a comma might take more time than the separate queries is not valid because in the both the case it will perform quite well but the more optimised way would be the second one as the DOM will change only once whereas for the 3 seperate queries the DOM will update thrice which will be costly.
Upvotes: 0
Reputation: 76
The second one has the advantage that you only access and go through the whole DOM tree once, this is what will create a performance boost. Reducing DOM access is one of the main factors when you want to increase performance of a browser application.
For example, when you create a table with a lot of cells like this with JQuery:
var table = $('<table>');
for(var i = 0; i < 1000; i++){
var row = $('<tr>');
for(var j = 0; j < 10; j++){
var col = $('<td>MyCell</td>');
row.append(col);
}
table.append(row);
}
You can create a high performance boost by removing a lot of the JQuery $('...') calls, by concatenating a big string and add the string as html to the table:
var table = $('<table>');
var htmlString = "";
for(var i = 0; i < 1000; i++){
htmlString += '<tr>';
for(var j = 0; j < 10; j++){
htmlString += '<td>MyCell</td>';
}
htmlString += '</tr>';
}
table.html(htmlString);
In above example, where 10'000 cells are created, you can have a performance improvement of 99%. When you only reduce 2 calls to $('...') the performance boost won't be significant, unless your code is inside a loop.
Upvotes: 1
Reputation: 23798
The first snippet differs from the second snippet by way of 3 function calls to a single function call.
Obviously, JQuery can perform well in the second way of calling
Upvotes: 1