3

Are there rules or best practices to write JavaScript code that is not memory hungry?

Back in time when I had to allocate and deallocate each byte in my software, I had a good picture of memory usage in my mind. But now I am alsways uncertain. All those cross and circular references, closures, duck typing, I got used to those great features but always feel uncertain about the memory effectivnes.

7
  • 1
    Have you taken a look at this before? developer.mozilla.org/en-US/docs/Web/JavaScript/… Commented Sep 23, 2014 at 20:59
  • my answer is not use js ;) really -- but also I agree with Dai Commented Sep 23, 2014 at 21:01
  • Well, knowing how your car works and how it is designed is one thing, but having a good set of practical rules how not to kill it too fast is another thing. Commented Sep 23, 2014 at 21:04
  • 1
    Are you referring to client-side JS (browser related) or server side (node.js)? While some fundamentals might be the same, I believe the actual answer will be quite different depending on this. Commented Sep 23, 2014 at 21:04
  • possible duplicate of Javascript memory management pitfalls? Commented Sep 23, 2014 at 21:52

1 Answer 1

0

Anytime you exit a scope, the garbage collector does its job. So if you move some code to a function that executes and ends, all of the variables will be garbage collected when the function is over (except for the ones that were available before the function was called in the first place).

Sign up to request clarification or add additional context in comments.

7 Comments

What about objects in function scope that are also closed over? The statement "executes and ends, all of the variables will be garbage collected when the function is over" is incorrect.
Local objects are garbage collected when the function scope is over, no?
No. That's just not how it works. The garbage collection algorithms used by browsers take varying routes, but none of them go for "function ended, garbage collect". Closures are a fundamental part of Javascript and GCing function scoped variables at function end time would decimate this concept.
Isn't a closure and the inner part of a function basically the same thing?
All modern browsers use the Mark-and-sweep algorithm for GC. It's not enough to do reference counting. You can read more about this here: developer.mozilla.org/en-US/docs/Web/JavaScript/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.