Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance vs readability: multiple selectors vs. multiple statements in jQuery/JS

I'm writing some jQuery code that hides or displays numerous table columns from a large table at the same time. I wanted to know if it would be faster to use code like this:

$("selector 1, selector 2, selector 3").css("display", "none");

or code like this:

$("selector 1").css("display", "none");
$("selector 2").css("display", "none");
$("selector 3").css("display", "none");

So I used jsperf.com to create a performance test case. With that I established that the first type of code (which uses one long string with multiple selectors) is faster than the second type of code (which hides columns one at a time) by about 53%. However, by the time I'm done writing it, it will be borderline unreadable, looking something like this:

$("#table tr *:nth-child(4), #table tr *:nth-child(5), #table tr *:nth-child(6), #table tr *:nth-child(7), #table tr *:nth-child(8), #table tr *:nth-child(9), #table tr *:nth-child(10), #table tr *:nth-child(11), #table tr *:nth-child(12)").css("display", "none");

So my question is, which is the greater evil for jQuery/JS code--inefficient performance, or lack of readability? My background is in Python so I tend to value readability above performance, and 53% doesn't seem like a huge drop-off in real world terms. But on the other hand, I plan to minify my JS code once I deploy it, so it will end up not being readable anyway...though I know there are de-minifiers out there that can return my code to its original readable or unreadable form. As you can see I can talk myself around in circles on this topic, and I'm not looking to start a debate or discussion, so I'm just posting this here in case there's a generally accepted way of handling this in the jQuery/JS community.

like image 498
GChorn Avatar asked Dec 15 '22 12:12

GChorn


1 Answers

You could store the selectors in an array, then join them when needing them:

var selectors = [
    "selector 1",
    "selector 2",
    "selector 3"
];
$(selectors.join(", ")).css("display", "none");

The reason your long selector works is because only one jQuery object is created, and only one browser method could be called, improving speed. I'm guessing document.querySelectorAll would be used, and can be passed that whole selector and return results. While jQuery would be calling n number of document.querySelectorAll methods for n number of $().css calls.

Another option, is to use the .add method to "improve" readability:

var selectors = $("selector 1");
selectors.add("selector 2");
selectors.add("selector 3");
selectors.css("display", "none");

Although I'm sure this will be faster than the multiple selector/css statements, it won't be as fast as document.querySelectorAll's capability with one big selector.

like image 144
Ian Avatar answered May 17 '23 12:05

Ian