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):
var array = 'months|monthsShort|weekdays|weekdaysShort|weekdaysMin|longDateFormat|calendar|relativeTime|ordinal|meridiem'.split('|');
var array = ['months','monthsShort','weekdays','weekdaysShort','weekdaysMin','longDateFormat','calendar','relativeTime','ordinal','meridiem'];
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
, where n
is the number of elements, the 11 is for the .split('|')
For the array version, that's 2 + 3 * (n - 1)
, the 2
for the []
.
That means that as soon as you have 6 elements, the .split
version is shorter:
for(var i = 5; i < 8; i++){
console.log('Elements:', i, 'split:', 11 + (i-1), 'array:', 2 + 3 * (i-1));
}
// Elements: 5 split: 15 array: 14
// Elements: 6 split: 16 array: 17
// Elements: 7 split: 17 array: 20
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With