Go中的短路评估 [英] Short circuit evaluation in Go

查看:79
本文介绍了Go中的短路评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对短路评估的理解是,仅在if语句中需要时才调用表达式.Go会遵循吗?

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")
}

...对此:

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

...因为 isValidQueryParams 是一个比 r == nil 或测试地图长度要大得多的开销的函数?

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

即解释器将首先评估r == nil,看到它是正确的,而不用费心评估其他条件吗?

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

错误地将短路评估称为惰性评估

Incorrectly referred to short circuit evaluation as lazy evaluation

推荐答案

感谢Kostix和mkrieger的回答-他们是正确的,我指的是短路评估,而不是惰性评估.

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

Go确实实现了正常的短路评估,可以通过以下代码推导出来

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

这篇关于Go中的短路评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆