I'm working on a Javascript app which does a lot of per-pixel operations on arrays which represent image data. When I'm setting up the arrays, I start with an empty '[]' and then fill it up with zeros, a bit like this:
<!DOCTYPE html>
<html>
<head>
<script>
function makeBigArray()
{
// Create a data array for a 5000*5000 RGB image
var imageData = [];
for (var i = 0, lenI = 5000*5000*3; i < lenI; i++)
{
imageData.push(0);
}
}
</script>
</head>
<body>
<button onclick="makeBigArray()">Make Big Array</button>
</body>
</html>
I noticed quite quickly that a loop like this causes what seems to be a massive memory hit. When I execute the above code, I get memory usages in the 2GB range.
Can someone explain why simply pushing elements into an array like that creates such high memory usage?