Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Avoiding garbage is relatively straight forward. You need to understand where the allocations are being made and see if you can avoid the allocation.</p> <p>First, declaring variables at the beginning of a function will NOT help. The compiler does not know the difference. However, human's will know the difference and it will annoy them.</p> <p>Use of an array instead of a slice will work, but that is because arrays (unless dereferenced) are put on the stack. Arrays have other issues such as the fact that they are passed by value (copied) between functions. Anything on the stack is "not garbage" since it will be freed when the function returns. Any pointer or slice that may escape the function is put on the heap which the garbage collector must deal with at some point.</p> <p>The best thing you can do is avoid allocation. When you are done with large bits of data which you don't need, reuse them. This is the method used in the <a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling tutorial</a> on the Go blog. I suggest reading it.</p> <p>Another example besides the one in the profiling tutorial: Lets say you have an slice of type <code>[]int</code> named <code>xs</code>. You continually append to the <code>[]int</code> until you reach a condition and then you reset it so you can start over. If you do <code>xs = nil</code>, you are now declaring the underlying array of the slice as garbage to be collected. Append will then reallocate xs the next time you use it. If instead you do <code>xs = xs[:0]</code>, you are still resetting it but keeping the old array.</p> <p>For the most part, trying to avoid creating garbage is premature optimization. For most of your code it does not matter. But you may find every once in a while a function which is called a great many times that allocates a lot each time it is run. Or a loop where you reallocate instead of reusing. I would wait until you see the bottle neck before going overboard.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload