0

Are JavaScript strings cached so that if I create a string that already exists elsewhere, there is only one instance of the string and it is shared?

Example:

function rgbString(r, g, b, a) {
  if (a === 1) {
    return "rgb(" + r + "," + g + "," + b + ")";
  } else {
    return "rgba(" + r + "," + g + "," + b + "," + a + ")";
  }
}

If this gets called several times:

rgbString(255,0,0,1)
"rgb(255,0,0)"
rgbString(255,0,0,1)
"rgb(255,0,0)"
rgbString(255,0,0,1)
"rgb(255,0,0)"
rgbString(255,0,0,.5)
"rgba(255,0,0,0.5)"
rgbString(255,0,0,.5)
"rgba(255,0,0,0.5)"

producing multiple identical strings, some with/without alpha, is there only one version of identical strings?

rgbString(255,0,0,.5) === rgbString(255,0,0,.5)
true

shows they evaluate to the save value but that does not mean they are shared/cached.

I don't think Chrome's profiler can help due to strings likely being "native" memory, thus beyond the scope of the heap profiler.

Note: this was marked as a dup of another question. I'm somewhat satisfied but not completely.

The prior question was solely about speed of comparison, then presuming fast speed implied "interning".

I am interested in memory efficiency, not cpu speed. Although the indirect proofs of interning are interesting, I want a very concrete answer for a technique to prove that any method used to create identical strings results in only one in memory. This is difficult due to the difference in "native" memory and the JS heap.

Is there a way to be certain that identical strings are stored only once?

backspaces
  • 3,802
  • 6
  • 34
  • 58
  • I think you should [ask a new question](http://stackoverflow.com/questions/ask) "*How to measure memory consumption of (possibly interned) strings in JavaScript?*". The main question of this post was "*Are JavaScript strings [interned] so that if I create a string that already exists elsewhere, there is only one instance of the string and it is shared?*" which imho is answered pretty well in the dupe. – Bergi Dec 09 '14 at 02:54
  • 1
    I agree, much better form of the question. I'm building a simulation system, http://agentscript.org, that typically has a million "patches", a million "agents" and a million "links" between the agents. Using a few simple tests, we've found even tiny misunderstanding of JS memory system leads to disaster. Our most recent "massive JS" stunt was to read in 91MB seismogram images and analyze their traces. Makes one careful indeed. Boy do you learn to love Typed Arrays! – backspaces Dec 09 '14 at 04:36

0 Answers0