DEV Community

Discussion on: StringBuffer in Dart

Collapse
 
mraleph profile image
Vyacheslav Egorov

"So literally the garbage collector is called for every item you concatenate" - this is not true, GC does not happen on every concatenation. It is true that every concatenation allocates a new string, though.

If you use string builder then you might want to go all in and do: sb.write(city); sb.write(" "); instead of doing concatenation and then adding it to the builder.

Yet better way is simply to do cities.join(" ").

Collapse
 
infiniteoverflow profile image
Aswin Gopinathan

Ohh ! That i didnt know about GC. Thanks for letting me know. Will keep that in mind.

So i have a doubt. When will the GC be called then for disposing the previously allocated memory ?

Collapse
 
mraleph profile image
Vyacheslav Egorov

When GC heuristics decide that it is time to do so. There are multiple things GC monitors (e.g. how much space is used in the nursery, how much space is used in the old space, etc) and few external signals (e.g. Flutter can tell Dart that it's in between frames and Dart has time to do GC, OS can tell Flutter that memory is getting low - which Flutter will then forward to Dart, etc). GC takes all of this into account and decides when and what to do. It's a pretty complicated logic which tries to find balance between memory usage and performance.

Thread Thread
 
infiniteoverflow profile image
Aswin Gopinathan

Okay ! Now i get it.
It's really interesting how GC is handled in Dart. Makes me wanna explore more on that !

Thanks again for sharing your insights.

Thread Thread
 
mraleph profile image
Vyacheslav Egorov

FWIW GCs are never invoked after each allocation - that would be prohibitively expensive, so there is nothing Dart specific here.

You might have been thinking about how some languages use reference counting which would free the memory occupied by an object immediately after the last reference to it disappears.

Thread Thread
 
infiniteoverflow profile image
Aswin Gopinathan

Yeah, i have been following the same concept here. Guess i didnt go about it the right way !

So, the languages that incorporate reference counting approach to freeing a memory immediately is less efficient ? Or did i miss anything ?

Collapse
 
bhaskarjha profile image
Bhaskar Jha

This is was i was also thinking, if we are supposed we concatenation operator as argument of .write() then enventually our space problem similar. Thanks for comment. Cleared many thing. 😊