by fabiospampinato · 4y ago · 0 comments
Example: you split a string into words for spell-checking purposes, once you've spell-checked each word you cache it so that you don't have to ask the spell-checker again if it's valid or not, now each time the original string is edited every single intermediate string produced during the edit could be kept in memory just because you are caching a word out of each of them. This can get out of hand super quickly.
Each time you are extracting a string out of another string this problem can arise.
Another example of how rough this can be is any program speaking over a network because it's really easy to end up with every network packet you've ever gotten (more or less) hanging around in memory because you've got this or that tiny bit of some string that was constructed to represent some chunk of the stream.
Surprised to see it in a javascript context, though. I'd have thought they'd have long since passed the point where they found out they have to take copies.
I ended up writing a hack-string-copy function "substrForceMemCopy" that forced the runtime to allocate a new string by using substr on one less character than I actually wanted and then adding that missing character to force creation of a new string.
Main part of the function:
return s.substr(start, length - 1) + s.charAt(start + length - 1);I'm not an expert in this space, but it seems to me that the JavaScript engine could eventually clean up that memory, maybe based on some heuristics (e.g. the size of the original string, whether any references to the original string exist, etc.).
"Issue 2869: Substring of huge string retains huge string in memory"
Status: Assigned (Open)
Reported 2013