Go is strong typed and object oriented by definition. To distinguish bad habits, benchmarking against the compiler performance is often convincing.
Logic
- The most efficient loop is using a locally defined variable
- Don't bother to use anything but the len() to get the size of an array
- Don't duplicate code to handle the first item of a list
- Don't try to keep a single exit
- Always use shadowing inside a for loop even for a boolean.
- Don't bother about irrelevant cases in a switch.
- Use bit masking instead of a second if.
- Get the bits representation of a byte using bits package is simple and efficient.
Math
- math.Log2() is the most efficient to check that 2 is the sole divisor.
Arrays
- Array of struct is as efficient as multiple arrays.
- Array initialization using append is costly.
- Using a method is marginally more efficient to add an element to an array.
Templates
- Use implicit parsing for forms
- Keep a global var to hold a template read from file
Buffers
- No difference when writing to file
- Returning a buffer as a string is marginally more expensive.
- Package
io
is much more efficient thanfmt
which offers many more possibilities: - When handling every byte of a buffer, use ReadByte.
Builder
- No difference for a url builder between returning the string or the url.URL.