Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory management with Javascript static classes and methods

I wanna know how these things works.

class Test {
    whatIsMyName(name) {
        this.name = name;
    }
    tellMyName() {
        return this.name;
    }
}

let a = new Test();
a.whatIsMyName("Bob");
a.tellMyName(); // "Bob"

Browser assigns a part of memory to variable a.
Browser keeps the memory until I refresh the website.

class Test {
    static whatIsMyName() {
        const name = "Bob";
        return name;
    }
    static tellMyName() {
        return Test.whatIsMyName();
    }
}

Test.whatIsMyName(); // "Bob"
Test.whatIsMyName(); // "Bob"
Test.tellMyName(); // "Bob"

Does browser assign another part of memory when I call it more than one?

like image 480
John Doe Avatar asked Sep 27 '26 13:09

John Doe


1 Answers

Does browser assign another part of memory when I call it more than one?

Very likely, yes². It has to allocate the string "bob", and it creates a local variable name. Both consume memory. As you do neither create a closure or store the string somewhere, all references to it will be lost after every of these calls, thus garbage collection might free the memory directly afterwards.

² modern js engines do a lot of clever optimizations though, maybe they optimize things away ...

like image 164
Jonas Wilms Avatar answered Sep 30 '26 02:09

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!