Short circuit evaluation in Go

Issue

My understanding of short circuit evaluation is that an expression is only called when needed in an if statement. Does Go follow this?

For instance, would I get better performance on average from:

if !isValidQueryParams(&queries) || r == nil || len(queries) == 0 {
    return "", fmt.Errorf("invalid querystring")
}

…to this:

if r == nil || len(queries) == 0 || !isValidQueryParams(&queries) {
    return "", fmt.Errorf("invalid querystring")
}

…since isValidQueryParams is a function with much more overhead than r == nil or testing the length of a map?

i.e. will the interpreter evaluate r == nil first, see it’s true and not bother to evaluate the other conditions?

EDIT: Incorrectly referred to short circuit evaluation as lazy evaluation

Solution

Thank you to Kostix and mkrieger for their answers – they are correct, I’m referring to short circuit evaluation and not lazy evaluation.

Go does implement normal short circuit evaluation, as can be deduced with the following code:

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        if testFunc(1) || testFunc(2) {
            // do nothing
        }
    }
}

func testFunc(i int) bool {
    fmt.Printf("function %d called\n", i)
    return true
}

…which will always give:

$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called

Answered By – stizzo96

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.