Memory management is a way of assigning memory from your machine memory to your application and then releasing that memory back to your machine when no longer in use.
Before
After
1. Reference count - Python, PHP
2. Mark and Sweep - Javascript
All the objects initially have their marked bits set to false
All Reachable objects have their marked bits changed to true.
Non reachable objects are cleared from the memory.
A Memory leak can be defined as a piece of memory that is no longer being used or required by an application but for some reason is not returned back to the OS and is still being occupied needlessly.
function foo() {
bar = "this is a hidden global variable";
}
function foo() {
this.variable = "potential accidental global";
}
foo();
undeclared variables: forgot to use var to declare it
a reference to an undeclared variable creates a new variable inside the global object
accidental global variable can be created is through this
To prevent these mistakes from happening,
add 'use strict'; at the beginning of your JavaScript files.
const arr = [1, 2, 3, 4, 5, 6, 9, 7, 8, 9, 10];
const used = process.memoryUsage();
console.log(`used: ${JSON.stringify(used)}`);
for (let key in used) {
console.log(`${key} ${Math.round(used[key] / 1024 / 1024 * 100) / 100} MB`);
}
Output:
let arr = Array(1e6).fill("some string");
const used = process.memoryUsage();
for (let key in used) {
console.log(`${key} ${Math.round(used[key] / 1024 / 1024 * 100) / 100} MB`);
}
Output:
const express = require('express')
const app = express();
const port = 4000;
const leaks = [];
app.get('/bloatMyServer', (req, res) =>
{
const redundantObj =
{
memory: "leaked",
joke: "meta"
};
[...Array(10000)].map (i => leaks.push(redundantObj));
res.status(200).send({size: leaks.length})
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));