Hacker News new | ask | show | jobs
by coder543 1312 days ago
There is potentially another option: use the midstack inliner to move the allocation from the heap to the stack of the calling function: https://words.filippo.io/efficient-go-apis-with-the-inliner/

As long as the global slice is never mutated, the current approach is probably fine, but it is definitely a semantic change to the code.

3 comments

That seems like overkill for this particular case, but it's a very interesting technique, thanks for the link!
Why doesn't go use RVO like C++ and Rust?

https://en.wikipedia.org/wiki/Copy_elision#Background

I don’t think we’re on the same page about what midstack inlining is being used for in my suggestion. This discussion is about eliminating a heap allocation, which as far as I understand, RVO never does. Please read the article I linked if you want to discuss this further. I don’t want to repeat the article pointlessly.

I’m also fairly sure Go uses RVO here too, which cuts down on the number of times the object is copied around, but again, it’s irrelevant to the discussion of heap allocations. Copying the object isn’t the performance problem here, needlessly allocating a very short-lived object on the heap over and over is.

Packages should be exposing an API with destination slices more often to begin with. The stdlib is pretty good about this (there's a few missing though 1.19 closed the most obvious absences), but most third-party code is awful. Or worse, it only takes strings.