I often notice when people split a string of substrings instead of just declare an array of the necessary strings.
Example in moment.js:
langConfigProperties = 'months|monthsShort|weekdays|weekdaysShort|weekdaysMin|longDateFormat|calendar|relativeTime|ordinal|meridiem'.split('|'),
Example in jQuery
"Boolean Number String Function Array Date RegExp Object".split(" ")
What is a reason to prefer such way ?
It’s way slower to use the
.split, but it has the advantage that the code can be shorter (Less characters):In this example, the difference isn’t huge, but if you have 100 variables, the difference gets more significant.
The length added by the delimiter in the split version is
11 + 1 * n, wherenis the number of elements, the 11 is for the.split('|')For the array version, that’s
2 + 3 * (n - 1), the2for the[].That means that as soon as you have 6 elements, the
.splitversion is shorter: