简体   繁体   中英

What is the difference between Appender and ~?

I have read that if I often allocate strings I should use Appender , but what of principle work of Appender is different from ~ operator?

Both (afaik) of them is use GC for memory allocation. So what is the difference? And where one better then another?

So it is the ~= operator that appender replaces, not the ~ one. ~ always makes a new copy without actually appending to the existing one (it leaves the old one unchanged) which makes it an inefficient convenience that you should generally avoid when performance matters.

But anyway, ~= and appender aren't actually that much different. The key difference is ~= keeps its capacity cache in the GC where as Appender carries it with it. If you are just using a small number of arrays close to each other, you probably won't notice a difference between the two.

But, if you are doing many arrays with a lot of appending at the same time, or doing anything multi-threaded, then Appender's local capacity storage will give you a pretty big boost because it avoids a global lock when asking the GC for its capacity cache and ensures you don't thrash that global cache as you switch between the different arrays.

Appender also happens to be an encapsulated output range, so you can pass it to some functions expecting that interface, though you can use regular arrays for that too with the right imports in most circumstances.

So, if you are just appending to one array in a loop, go ahead and use ~= , and you probably won't notice a difference (in fact, I have personally found ~= is a wee bit faster in these circumstances, but the difference is negligible with building with optimizations) but if you are storing the appender itself (rather than just the final result) or doing several arrays at once, or writing a multi-threaded program, then Appender can give you a significant boost because it avoids contention when using that global GC cache.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM