问题
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!
回答1:
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.
来源:https://stackoverflow.com/questions/50854916/javascript-memory-impact-of-null-vs-undefined