I’ve been running some tests to see if I can find an efficient selector for controls prefixed with the id of parent controls in Asp.Net
I’ve been looking for this as I was to be able to select Asp controls from external javascript files (I’m fed up of using ClientID).
To test I set up a page with 150 textboxes all with the cssclass “speedy” and an individual id and ran the following code to select the 107th textbox.
function testclientInput() {
var iterations = 100;
var totalTime = 0;
// Record the starting time, in UTC milliseconds.
var start = new Date().getTime();
// Repeat the test the specified number of iterations.
for (i = 0; i < iterations; i++) {
// Execute the selector. The result does not need
// to be used or assigned to determine how long
// the selector itself takes to run.
// All tests done in ie6, ie7, ie8, ie9beta, firefox3.6, opera11 & chrome8
// slowest
// $('input.speedy[id$=_TextBox107]');
// Quick but only useful if you know the index.
//$($('input.speedy')[106]);
//$('[id$=_TextBox107]:first');
//$('input[id$=_TextBox107]');
//$.clientID("TextBox107");
//$('[id$=_TextBox107]');
//$('input[id$=_TextBox107]:first');
//$($('[id$=_TextBox107]')[0]);
// Fastest
//$($('input[id$=_TextBox107]')[0]);
}
// Record the ending time, in UTC milliseconds.
var end = new Date().getTime();
// Determine how many milliseconds elapsed
totalTime = (end - start);
// Report the average time taken by one iteration.
alert(totalTime / iterations);
};
This is the best I have come up with. $($('input[id$=_TextBox107]')[0]);. The results have been surprising…. I expected using the :first selector to match my version but it reported much slower results.
Can anyone think of a way to optimize this?
It will depend on the browser.
This version:
…is a valid
querySelectorAllselector, so any browser that implements it will be very fast.If you use the
:firstselector, you’re using something that is not a valid CSS selector, so it defaults to Sizzle’s javascript based selector engine, and will be much slower.If performance is crucial, then don’t use jQuery for this. You can just use
document.getElementsByTagName(), and filter the one(s) you want, if the browser doesn’t supportquerySelectorAll.