Standard Library

Bytes

bytes.Equal is a specialized way to compare byte slices. It’s much faster than simply comparing two slices with a for loop. Something worth being aware of, the bytes.Equal function considers empty and nil slices to be equal, while reflect.DeepEqual does not.

bytes.Compare function to compare two slices of bytes.

Logging

log.Fatal and log.Panic

When logging with the Go log package there’s a trap waiting for you in the log.Fatal and log.Panic functions. Unlike what you might expect of a logging function these don't simply log a message with a different log level, they also terminate the whole application. log.Fatal cleanly exits the application, log.Panic invokes a runtime panic. Here are the actual functions from the Go log package:

// Fatal is equivalent to Print() followed by a call to os.Exit(1).
func Fatal(v ...interface{}) {
    std.Output(2, fmt.Sprint(v...))
    os.Exit(1)
}

// Panic is equivalent to Print() followed by a call to panic().
func Panic(v ...interface{}) {
    s := fmt.Sprint(v...)
    std.Output(2, s)
    panic(s)
}

Time

time.LoadLocation reads from a file

To convert between time zones you first need to load location information. It turns out that time.LoadLocation reads from a file every time it's called. Not the best thing to do when formatting each row of a massive CSV report:

package main

import (
    "testing"
    "time"
)

func BenchmarkLocation(b *testing.B) {
    for n := 0; n < b.N; n++ {
        loc, _ := time.LoadLocation("Asia/Kolkata")
        time.Now().In(loc)
    }
}

func BenchmarkLocation2(b *testing.B) {
    loc, _ := time.LoadLocation("Asia/Kolkata")
    for n := 0; n < b.N; n++ {
        time.Now().In(loc)
    }
}

Last updated