问题
I profiled my nodejs application and see some strange strings, it's marked as parent in (sliced string).
I using v8-profiler and node-inspector.
Here is photo of profiler screen (sorry for photo, not screenshot, just my system really overloaded and don't have enough space to make screen): http://i.imgur.com/dkkPbGA.jpg
So, my question, what is this parent in (sliced string) strings?
UPD: After some review looks like i understand, when i made slice on string, it's stored parent string (is it optimization?). In result this parents strings was in memory. After i copied this spliced strings, looks like there this parent strings was cleaned from memory. Am i right?
回答1:
Yes, it's an optimization. When you have a long string var longstring = "abc..."
, and you create a substring (a.k.a. "slice") from it var short = longstring.substr(20, 30)
, then the characters are not actually copied around in memory; instead short
is internally just represented as a slice of |longstring| beginning at index 20 with a length of 30
, and longstring
is called short
's "parent". As long as your code keeps a reference to short
, longstring
cannot be freed by the garbage collector.
(For the record, we (V8 developers) know that this optimization can have negative effects on memory consumption, because it can cause long strings to be kept alive when just copying out the part that's still needed would use less memory. The problem is that in the general case, calculating whether that operation makes sense (because only a short chunk is still required) or not (because there are many overlapping slices which, when added up, would account for more memory than their shared parent), is fairly expensive and would make the garbage collector quite a bit slower.)
来源:https://stackoverflow.com/questions/32813720/nodejs-profiling-parent-in-sliced-string