How does JavaScript represent strings and Date objects in memory?
Context and Intent
I'm mostly just curious, but here's what led to the question: We have code in our React front end that accepts JSON payloads from our API, and those payloads include dates -- in ISO-8601 UTC string form (e.g. 2023-02-01T17:01:08Z
), of course.
As we pass the resulting model object around a variety of hooks, components, functions, etc., we keep it as a string, and we only parse it into a Date object if we are going to display it or use it to make decisions. In some cases, this means that we'll re-parse the same string into a Date multiple times in the course of rendering the UI. In other cases, we ignore the Date completely as it's not relevant for the page.
I'm trying to reason about whether it would be worthwhile to modify our system such that we always parse Date strings into actual Date objects upon receipt from our API. Our UI is written in TypeScript -- AFAIK this makes no difference with regard to my actual question -- and my biggest motivator in wanting to make this change is the improved type safety and clarity.
To be clear, time performance is the bigger concern, but I can do my own benchmarking. For the purposes of this question, I'm asking about memory performance, as much for my own understanding and education as for any technical decisions that might result, but I always try to understand the full scope of any tradeoff.
I imagine that this could be implementation dependent; if so, I'm most interested in the facts as they apply to modern versions of Google Chrome (with default configuration, if that matters), but happy to learn about other implementations as well.
Questions
If I take a 20-character ISO-8601 UTC string and parse it into a Date, how much memory would the resulting Date use? Does JavaScript work like Java, using an 8-byte "long" integer to store dates as milliseconds since the epoch? I found disappointingly little information about this in my searching; most of the results I found were actually about Java.
Also, how much memory does the string use? What's Javascript's internal string encoding? A quick Google indicates that it uses UTF-16 (and therefore 40 bytes for the 20-character date string)?
For both Date and String, are there any differences in applicable overhead? Are there optimizations that might apply to either Strings or Dates and affect the result (e.g. string interning -- which if I am understanding this correctly, JS does, but it would not apply to my use case since the value came from an API response)?