Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the advantage of "a,b,c".split(",") over ["a","b","c"]?

Tags:

javascript

I've seen this in a couple of places, most notably the plugins.js file of HTML5 Boilerplate, and I'm not sure why.

What's the motivation behind using something like

var d = "header,nav,footer".split(",");

instead of

var d = ["header", "nav", "footer"];

?

like image 436
wlangstroth Avatar asked Dec 10 '22 03:12

wlangstroth


2 Answers

Under the inexorable pressure of Moore's Law, it's important to find ways for software to consume more CPU cycles to do the same work. Your particular case (using split instead of writing out what you mean in the first place) is an example of "micro-deoptimization".

While there are much more efficient ways to gain inefficiency (code generation templates, preprocessors, and similar tools), it's important for programmers to have a large repertoire of such tricks at hand.

like image 157
Ted Hopp Avatar answered Dec 11 '22 18:12

Ted Hopp


Often people prefer being able to write stuff inside a single string instead of having to write separate strings with quotes etc.

However - when possible - it's usually nicer to do it with space instead of comma since in many languages the split() function will use them as a default delimiter if no arguments are specified.

But all in all - it's just a matter of what the developer prefers to write. It's certainly not faster but the difference does not matter at all (you are not going to call this a billion time anyway, are you?)

like image 20
ThiefMaster Avatar answered Dec 11 '22 16:12

ThiefMaster