drxzpo70788179614 2018-12-11 10:37
浏览 55
已采纳

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

...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

  • 写回答

3条回答 默认 最新

  • dstd2129 2018-12-11 10:52
    关注

    What you're referring to is called "short circut evaluation"—that is, the subexpressions are evaluated using the normal associativity rules only for as long as the complete result is available and evaluation of the rest of the expressions won't change it according to the rules of the binary operator(s) in question.

    Go does implement short circuit evaluation of logical expressions (see the other answer).

    (@icza commented: Somewhat related: there is short circuit evaluation in Go code, but Go's template engine does not use short circuit evaluation. Details: Golang template and testing for Valid fields.)

    "Lazy evaluation" is completely another thing—usually implemented in the so-called "functional" programming languages, and it's not directly implemented in Go.


    Having said that, I'd note that while Go does not have direct (as with the syntax and runtime) support for lazy evaluation, it may be used where needed.

    For instance, you may have a goroutine reading potentially infinite number of items from a channel, and processing them in one way or another, and another goroutine—or several of them—producing these values and sending them through the channel. This way, the values only "materialize" at the receiving end no faster than they are actually ready to be handled.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于#flink#的问题:关于docker部署flink集成hadoop的yarn,请教个问题flink启动yarn-session.sh连不上hadoop
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题