I
I
Ilya2021-07-22 12:28:19
go
Ilya, 2021-07-22 12:28:19

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
}


So, if you look at the addresses of the incoming and outgoing slice, then they naturally change (up to a certain threshold). But I'm interested in how the compiler perceives such a construction and are there any memory leaks?

UPD: Let me rephrase the question. Do previous slices (which are small) slip into the heap and get lost there. Because the buffer is replaced as a result of the growth of elements and the slices are removed from the function for further use in the general scope.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2021-07-22
@pav5000

"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 question

Ask a Question

731 491 924 answers to any question