Optimizing memory consumption in JavaScript
All created variables are stored in the computer RAM. Sometimes thoughtlessly writing code can dramatically increase memory consumption.
Let's look at an example. Let us face
the task of finding the sum of integers
from 1
to 100000000
. Let's
say we have a function that fills an
array with integers from a given range:
function fillArr(a, b) {
let res = [];
for (let i = a; i <= b; i++) {
res.push(i);
}
return res;
}
Let's also have a function that finds the sum of the array elements:
function getSum(arr) {
let sum = 0;
for (let elem of arr) {
sum += elem
}
return sum;
}
With a combination of these functions, you can easily solve the problem:
let sum = getSum(fillArr(1, 100000000));
It turned out to be an elegant solution. However, it has a problem: it consumes a huge amount of RAM.
Let's count. The fillArr
function
creates an array with 100000000
numbers. Let JavaScript allocate 2
bytes per number - then our array will
need 200000000
bytes to store,
which is something like 200
megabytes of RAM.
But in fact, much more RAM will be needed due to the fact that JavaScript has a very large overhead when storing an array.
Understanding the problem, it is easy to make a function that solves the problem and practically doesn't consume RAM:
function getNumsSum(max) {
let sum = 0;
for (let i = 1; i <= max; i++) {
sum += i;
}
return sum;
}
Let's solve the problem using our function:
let sum = getNumsSum(100000000);
A certain programmer was faced with
the task of finding the number of
numbers divisible by 7
without
a remainder that are in a given range.
He solved it like this:
let arr = [];
for (let i = 0; i <= 1000; i++) {
if (i % 7 == 0) {
arr.push(i);
}
}
console.log(arr.length);
Explain what is wrong with this code. Modify the code to a better one.
A certain programmer was faced with the task of finding the sum of the divisors of a number. He solved it like this:
function getDivisors(num) {
let res = [];
for (let i = 1; i <= num; i++) {
if (num % i === 0) {
res.push(i);
}
}
return res;
}
function getSum(arr) {
let sum = 0;
for (let elem of arr) {
sum += elem
}
return sum;
}
let sum = getSum(getDivisors(320));
console.log(sum);
Explain what is wrong with this code. Modify the code to a better one.