Garbage collection and correct usage of pointers in Go

后端 未结 2 818
日久生厌
日久生厌 2021-01-03 02:41

I come from a Python/Ruby/JavaScript background. I understand how pointers work, however, I\'m not completely sure how to leverage them in the following situation.

L

2条回答
  •  悲哀的现实
    2021-01-03 03:02

    Will the [...] be garbage collected correctly?

    Yes.

    You never need to worry that something will be collected which is still in use and you can rely on everything being collected once it is no longer used.

    So the question about GC is never "Will it be collected correctly?" but "Do I generate unnecessary garbage?". Now this actual question does not depend that much on the data structure than on the amount of neu objects created (on the heap). So this is a question about how the data structures are used and much less on the structure itself. Use benchmarks and run go test with -benchmem.

    (High end performance might also consider how much work the GC has to do: Scanning pointers might take time. Forget that for now.)

    The other relevant question is about memory consumption. Copying a string copies just three words while copying a *string copies one word. So there is not much to safe here by using *string.

    So unfortunately there are no clear answers to the relevant questions (amount of garbage generated and total memory consumption). Don't overthink the problem, use what fits your purpose, measure and refactor.

提交回复
热议问题