Skip to content

Instantly share code, notes, and snippets.

@nickserv
Last active August 29, 2015 13:57
Show Gist options
  • Save nickserv/9536886 to your computer and use it in GitHub Desktop.
Save nickserv/9536886 to your computer and use it in GitHub Desktop.
Go benchmark: Various methods of loading maps

Go benchmark: Various methods of loading maps

This benchmark was used for run.

Running

go test -bench=.

Note that there are no dependencies besides Go itself.

{
"c": "gcc % && ./a.out",
"clj": "clj %",
"coffee": "coffee %",
"go": "go run %",
"hs": "runhaskell %",
"jar": "java -jar %",
"lua": "lua %",
"ml": "ocaml %",
"py": "python %",
"rb": "ruby %",
"sh": "sh %",
"zsh": "zsh %"
}
package tmp
import (
"encoding/json"
"io/ioutil"
"path"
"runtime"
)
// callerDir returns the directory of this source code file in Run's
// implementation. Similar to __dir__ in Ruby.
func callerDir() string {
_, callerFile, _, _ := runtime.Caller(1)
return path.Dir(callerFile)
}
// getCommands gets the collection of supported commands. This is represented as
// a map of file extensions (strings) to commands (strings), loaded from the
// data file (commands.json).
func getCommands() (map[string]string, error) {
// Load the commands from the data file to a slice of bytes.
var commands map[string]string
jsonStream, fileErr := ioutil.ReadFile(path.Join(callerDir(), "commands.json"))
if fileErr != nil {
return commands, fileErr
}
// Parse the byte slice to get a map of type commands.
jsonErr := json.Unmarshal(jsonStream, &commands)
return commands, jsonErr
}
func getCommandsFast() (map[string]string, error) {
return map[string]string {
"c": "gcc % && ./a.out",
"clj": "clj %",
"coffee": "coffee %",
"go": "go run %",
"hs": "runhaskell %",
"jar": "java -jar %",
"lua": "lua %",
"ml": "ocaml %",
"py": "python %",
"rb": "ruby %",
"sh": "sh %",
"zsh": "zsh %",
}, nil
}
var commandsVar = map[string]string {
"c": "gcc % && ./a.out",
"clj": "clj %",
"coffee": "coffee %",
"go": "go run %",
"hs": "runhaskell %",
"jar": "java -jar %",
"lua": "lua %",
"ml": "ocaml %",
"py": "python %",
"rb": "ruby %",
"sh": "sh %",
"zsh": "zsh %",
}
package tmp
import (
"testing"
)
var result map[string]string
func BenchmarkGetCommands(b *testing.B) {
for n := 0; n < b.N; n++ {
result, _ = getCommands()
}
}
func BenchmarkGetCommandsFast(b *testing.B) {
for n := 0; n < b.N; n++ {
result, _ = getCommandsFast()
}
}
func BenchmarkCommandsVar(b *testing.B) {
for n := 0; n < b.N; n++ {
result = commandsVar
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment