I am trying to understand memory used by Strings & Arrays. As per this helpful question: How many bytes in a JavaScript string?
Blob
is a great way of checking byte size of Strings:
new Blob(['a']).size
-> 1
byte
But Strings are encoded UTF-16
in JavaScript which uses minimum of 2 bytes
. How does Blob
return 1?
Furthermore, -----
const x = 200;
const y = 200;
const changes = []
for (let i=0;i<y;i++) {
let subArr = []
for (let j=0;j<x;j++) {
subArr[j]= new Uint8Array(1)
}
changes[i]=subArr
}
console.log(new Blob(changes).size)
The array above consumes 79800
instead of 40000
(200*200 of Uint8Array(1)).
- Why does the array above consume double (79800) of what I expect (40000)? Also, why is the first index (0) interpreted as 1 byte and the following ones are 2 bytes ? Why is that?
'
for (let i=0;i<y;i++) {
changes[i] = new Array(x).fill(new Uint8Array(1))
}
- If I fill the array using the above, it still consumes
79800
. Why is that? As pointed out in comments, its the sameUint8Array
object that gets filledx
times.