0

I have a fairly large array in a node.js script I am writing that exists in the program's memory for only about a couple of seconds. The array stores metadata for some other (irrelevant) array in string format for about 6,000-7,000 items and when it is processed it is cleared from memory.

When a value in this array doesn't require any metadata I simply set the value to an empty string ''. However, I've recently been looking at changing the data type to undefined to save memory (there are 6k items in this array, after all.)

Are there any pros/cons for using an empty string vs. undefined in the realm of program optimization? Is it such a small difference that it doesn't even matter? Am I over thinking this silly thing?

I've looked at a similar question here: Memory overhead of empty array vs undefined var? in which they were using empty arrays instead of empty strings but I do not know if an empty string takes any less memory than an empty array.

Some clarification to the "memory worth" of these data types and some benchmarking would be greatly appreciated.

Brixster
  • 89
  • 1
  • 6

1 Answers1

1

The fact that you're coming to SO to ask this instead of doing your own profiling tells me that you don't need to be doing optimization yet.

Both undefined and an empty string should have a one-time allocation - undefined is actually a reference to a single value (and thus using it has no memory allocations beyond the initial engine setup) and strings in javascript are interned (which means if you use the same string literal twice it will refer to same string in memory twice) - which is why the following expressions will evaluate true:

"" === ""
"foo" === "foo"

but not these

[] === []
{} === {}

An empty string might result in fewer memory allocations than a new array if the JIT compiler, should one exist, does not infer that multiple instances of an empty array which is never modified as being replacable with a single empty array reference. But we can't know that that is the case for sure - it depends on the execution environment - which is why you should always profile your code against your target browsers before trying to optimize.

And this is all assuming, of course, that the memory allocations that are occuring are actually a problem. They might not be. Perfect is the enemy of the good enough :)

Dan
  • 10,282
  • 2
  • 37
  • 64
  • Haha, I've always wondered why the second example was always the case.. Really cleared up my idea of the JS engine - Thanks a million. – Brixster Dec 30 '19 at 03:41
  • NP. Please feel free to mark this answer as the accepted one if it answered your question - click the tickmark below the downvote arrow to do so :) – Dan Dec 30 '19 at 03:42
  • Will do.. Just waiting out SO's rate limit before I can accept your answer Lol – Brixster Dec 30 '19 at 03:43