HTML and CSS Reference
In-Depth Information
With the JSON way, the code will be somewhat shorter, although it is the JavaScript
equivalent of slicing bread with a chainsaw. Not only there is a performance impact in most
browsers , but you're also cutting down browser support quite a bit.
3
The main drawback of using array-based strings is their size in bytes. If you go with the
number method, you would use almost 2 characters per number (or, more precisely, 2N−1 ,
since you'd need one delimiter per number, except for the last one):
[ 0 , 1 , 1 , 0 , 0 , 1 , 1 ]. toString (). length // 13, for 7 values
So, for 512 numbers, that would be 1023 characters or 2 KB, since JavaScript uses UTF-16 4
If you go with the boolean method, it's even worse:
[ false , true , true , false , false , true , true ]. toString (). length // 37, also
for 7 values
That's around 5 to 6 characters per value, so 2560 to 3072 characters for 512 numbers (which
is 5 to 6 KB). JSON.stringify() even wastes 2 more characters in each case, for the opening
and closing brackets, but its advantage is that you get your original value types back with
JSON.parse() instead of strings.
Using A String
Using a string saves some space, because no delimiters are involved. For example, if you go
with the number approach and store strings like '01001101010111' , you are essentially
storing one character per value, which is 100% better than the better of the two previous
approaches. You can then get the values into an array by using String#split :
'01001101010111' . split ( '' ); //
['0','1','0','0','1','1','0','1','0','1','0','1','1','1']
Or you could just loop over the string using string.charAt(i) —or even the string indexes
( string[i] ), if you don't care about older browsers.
Using Bitfields
Did the previous method make you think of binary numbers? It's not just you. The concept of
bitfields is quite popular in other programming languages, but not so much in JavaScript. In a
5
 
Search WWH ::




Custom Search