7

I work in an area where memory utilization is very important to us, as we don't run on your classic web browsers / hardware.

We use null quite a lot in our application, one thing that has not been clear to me is if null takes up more space than assigning a variable to undefined.

Do we know if one or the other is more costly on memory usage?

Thanks for help!

mrkgregg
  • 73
  • 1
  • 4
  • Possible duplicate of [Does null occupy memory in javascript?](https://stackoverflow.com/questions/6499352/does-null-occupy-memory-in-javascript) –  Jun 14 '18 at 10:14
  • Check these answer: [What reason is there to use null instead of undefined in JavaScript?](https://stackoverflow.com/questions/6604749/what-reason-is-there-to-use-null-instead-of-undefined-in-javascript) – Yosvel Quintero Jun 14 '18 at 10:17

1 Answers1

5

As you can see in this jsperf test, null seems to be slightly faster in the chrome (V8, just like nodejs) which might indicate it being slightly more performant.

Since undefined is a longer string than null, the JIT compiler has to save 4 bytes more to memory when using undefined instead of null while parsing. Consider that memory aswell.

The garbage collection doesn't care about the value being either null or undefined. The difference should be minimal. You should consider the consequences regarding types of using null instead of undefined though. Enforcing the usage of either for the sake of performance might do more harm than good.

Tom M
  • 2,815
  • 2
  • 20
  • 47
  • 2
    Thanks Tom - appreciate the response! From my previous project, I used undefined exclusively because of the typeOf issue with null returning as an object which I think is what you're referring to. On this new project though, where memory usage is critical I thought I'd ask the question as I haven't found much in my research. Thanks again! – mrkgregg Jun 15 '18 at 20:25
  • You're welcome - but if you need full control over your memory, why don't you use another language like C#? You can manually allocate memory with that. – Tom M Jun 18 '18 at 07:48