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

I have seen this in several places, especially in the plugins.js HTML5 Boilerplate file , and I'm not sure why.

What is the motivation for using something like

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

instead

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

?

+4
source share
6 answers

Under the relentless pressure of Moore's Law, it is important to find ways for software to consume more processor cycles to do the same job. Your specific case (using split instead of writing what you mean first) is an example of "micro-optimization".

Although there is a much more efficient way to achieve inefficiencies (code generation templates, preprocessors, and similar tools), it is important that programmers have a large repertoire of such tricks at hand.

+12
source

Often people prefer to write things inside one line instead of writing separate lines with quotes, etc.

However - when possible - it is usually best to do this with a space instead of a comma, since in many languages ​​the split() function will use them as the default separator if no arguments are specified.

But overall, it's just a matter of what the developer prefers to write. This, of course, is not faster, but the difference does not matter (you are not going to call it a billion time in any case, are you?)

+1
source

This may be the result of incomplete refactoring: Perhaps the line was originally obtained from the configuration file (or it is planned to split it into a configuration file) or from user input. In this case, splitting from the string would be natural.

Or it might even match the style from another section that uses this input style. Maybe like this:

 function get_sections() { if has_config() { return get_config("sections").split(","); } return "header,nav,footer".split(","); } 

A third option may be to simplify the translation.

Not that I used it in any of these cases, but it might make sense for some developers.

+1
source

There is no advantage. In fact, this may be a little less efficient (I have not tested) to do with a method call on a string, but probably not so much.

This is only a personal preference. In addition, people tend to get a high level of use of string.split () in any language. This is pretty sexy.

0
source

Why write x * (1000/4) if you can write x * 250? I mean, why give runtime an additional headache for parsing strings, splitting (and the likelihood of errors due to lack of commas, commas inside strings, etc.) etc.? I see nothing but some strange coding convention when writing code in this way.

0
source

It’s easier to type because you have less quotation marks. Not suitable for something more complicated than a list of words.

0
source

Source: https://habr.com/ru/post/1388076/


All Articles