Does assigning a new string value create garbage that needs collecting?
garbage-collection, javascript, performance
Solution
Yes, strings need to be garbage-collected, just like any other type of dynamically allocated object. And yes, this is a valid concern as careless allocation of objects inside busy loops can definitely cause performance issues.
However, string values are immutable (non-changable), and most modern JavaScript implementations use "string interning", that is they store only one instance of each unique string value. This means that if you have something like this...
var s1 = "abc",
s2 = "abc";
...only one instance of "abc" will be allocated. This only applies to string values, not `String` objects.
A couple of things to keep in mind:
Functions like `substring`, `slice`, etc. will allocate a new object for each function call (if called with different parameters).
Even though both variable point to the same data in memory, there are still two variables to process when the GC cycle runs. Having too many local variables can also hurt you as each of them will need to be processed by the GC, adding overhead.
Some further reading on writing high-performance JavaScript:
- https://developer.mozilla.org/en-US/docs/JavaScript/Memory_Management
- https://www.scirra.com/blog/76/how-to-write-low-garbage-real-time-javascript
- http://jonraasch.com/blog/10-javascript-performance-boosting-tips-from-nicholas-zakas
Problem
Consider this javascript code: ``` var s = "Some string"; s = "More string"; ``` Will the garbage collector (GC) have work to do after this sort of operation? (I'm wondering whether I should worry about assigning string literals when trying to minimize GC pauses.) e: I'm slightly amused that, although I stated explicitly in my question that I needed to minimize GC, everyone assumed I'm wrong about that. If one really must know the particular details: I've got a game in javascript -- it runs fine in Chrome, but in Firefox has semi-frequent pauses, that seem to be due to GC. (I've even checked with the MemChaser extension for Firefox, and the pauses coincide exactly with garbage collection.)