0

When the V8 engine runs a script that refers to multiple string literals with the same contents, will it create a single location in memory for the string, towards which all the expressions will point to? Or will a separate memory location be allocated for every expression?

For instance, consider this little script:

let a = "asdf"
let b = "asdf"

After this runs, in the engine's internal representation of the variables, will a and b refer to the same location in memory?

(Bonus question: Is this behavior the same in other JavaScript engines, such as Internet Explorer's?)

Nicolas Trahan
  • 615
  • 2
  • 6
  • 13
  • It might, and it might not. There's no way you can tell. – Pointy Oct 22 '19 at 22:07
  • 1
    It should have separate memory location. If you have same memory location how can you change value of one variable? – Akash Bhandwalkar Oct 22 '19 at 22:36
  • I believe that strings in JS are immutable, so sharing memory locations wouldn't be a problem. – Nicolas Trahan Oct 22 '19 at 22:43
  • 1
    I hope the duplicate answers your question well enough. If you want a specific answer about the code example in the V8, please remove your bonus question and I'll happily reopen and wait for @jmrk to jump in (please ping me) – Bergi Oct 22 '19 at 22:47
  • I've taken a look at 2 very long strings in Chrome memory profiler. When the when the strings are the same (e.g. a==b), memory is at 2.5mb. If I change the code and make the strings different by one char, then memory is at 3.5mb. So it would seems that the compiler optimizes for same string literals. – Matt Oct 22 '19 at 22:50
  • No the linked answer is perfect, thank you @Bergi! – Nicolas Trahan Oct 22 '19 at 23:01

0 Answers0