Answer the question
In order to leave comments, you need to log in
How to conduct an escape analysis?
I'm wondering if this construction leaks memory:
I have a function that rasterizes a straight line between two given points (r0, c0)-(r1, c1), also taking a pointer to a buffer into which the coordinates are written ( ). Returns a buffer (not a pointer). In the body of the function, it usually expands to a certain threshold of elements through .type point struct{ r, c int}
append
func line(r0, c0, r1, c1 int, buffer *[]point) []point {
*buffer = (*buffer)[:0]
...
*buffer = append(*buffer, point{ ... })
...
return *buffer
}
Answer the question
In order to leave comments, you need to log in
"Memory leak" is not the correct term here. Most likely, you want to have fewer allocations, respectively, more performance.
1. It is better to pass a slice to the input not by a pointer. If the slice needs to be modified within a function, it's good practice to simply return the modified slice.
2. If you have a lot of appends there, then you should not forget to allocate a place inside the slice for these appends in advance, if their number is known.
For example, if you know that there will be 20 points in the buffer, then do: buffer = make([]point,0,20)
3. You can always compare several different implementations by writing benchmarks. https://scene-si.org/2017/06/06/benchmarking-go-pr...
If you use ReportAllocs, you will see in which option you have more allocations.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question