Someone recently told me that this is bad:
var el = $("#myID");
$(el).addClass("a");
$(el).addClass("b");
$(el).addClass("c");
and that it should be cached like so:
var $el = $("#myID");
$el.addClass("a");
$el.addClass("b");
$el.addClass("c");
So, my question is, why doesn’t it get optimized automatically? In Java and other languages I think that the compiler is smart enough to do the caching itself.
i.e., this:
// myList is a List<String>
String str = myList.get(0);
String trimmed = str.trim();
String sub = str.substring(0, 5);
boolean abc = str.startsWith("abc");
is no more efficient than this:
String trimmed = myList.get(0).trim();
String sub = myList.get(0).substring(0, 5);
boolean abc = myList.get(0).startsWith("abc");
Can anyone who knows more about compilers give me some insight here? Is JavaScript just stupid like that? Or is it also true for Java/others?
$(el)is a relatively expensive function call. The compiler cannot know that it will always return the same (or at least, an equivalent) object for each call, so it cannot make the optimisation you suggest.This is not necessarily a function of the language. I’m sure there will be languages (perhaps where you can declare a function as idempotent) in which the compiler CAN reason that the return value and do this optimisation.
I’m pretty sure the Java compiler/optimiser can do it for relatively simple cases.
So, for those same simple cases, there’s no reason why a Javascript compiler shouldn’t do it given the right circumstances. But it’s worth considering that the compilation happens in the browser, so there’s probably a limit to the amount of CPU time you want to spend doing optimisations so as not to impact the user’s browsing experience.