是否显式调用return函数

前阵子我被指责西蒙Urbanek从R核心团队(我相信)为用户推荐到显式调用return的函数结束时(他的评论被删除虽然):


foo = function() {

  return(value)

}

相反,他建议:


foo = function() {

  value

}

可能在这种情况下是必需的:


foo = function() {

 if(a) {

   return(a)

 } else {

   return(b)

 }

}

他的评论阐明了为什么return除非严格需要,否则不打电话是一件好事,但是已删除。


我的问题是:为什么不打电话return更快或更好,因此更可取?


HUWWW
浏览 644回答 3
3回答

繁花不似锦

如果每个人都同意return 在函数主体的末尾不需要不使用return的速度稍微快一些(根据@Alan的测试,相对于5.1秒为4.3微秒)我们都应该return在函数结尾处停止使用吗?我当然不会,我想解释原因。我希望听到其他人是否也同意我的看法。如果这不是对OP的直接答案,而是更长时间的主观评论,我深表歉意。我不使用的主要问题return是,正如Paul指出的那样,函数主体中可能还有其他地方需要使用它。而且,如果您被迫return在函数中间使用某个地方,为什么不使所有return语句都明确?我讨厌前后矛盾。我也认为代码读起来更好;可以扫描功能并轻松查看所有出口点和值。保罗使用以下示例:foo = function() {&nbsp;if(a) {&nbsp; &nbsp;return(a)&nbsp;} else {&nbsp; &nbsp;return(b)&nbsp;}}不幸的是,可能有人指出它可以很容易地重写为:foo = function() {&nbsp;if(a) {&nbsp; &nbsp;output <- a&nbsp;} else {&nbsp; &nbsp;output <- b&nbsp;}output}后一种版本甚至符合一些编程编码标准,这些标准倡导每个函数一个返回语句。我认为一个更好的例子可能是:bar <- function() {&nbsp; &nbsp;while (a) {&nbsp; &nbsp; &nbsp; do_stuff&nbsp; &nbsp; &nbsp; for (b) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;do_stuff&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (c) return(1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (d) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; do_stuff&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (e) return(2)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}&nbsp; &nbsp;return(3)}使用单个return语句重写起来会更加困难:它将需要多个breaks和复杂的布尔变量系统来传播它们。所有这一切都说明单一返回规则不能很好地与R配合使用。因此,如果您需要return在函数主体的某些位置使用它,为什么不保持一致并在各处使用它呢?我认为速度参数是无效的。当您开始查看实际上可以执行某些功能的函数时,0.8微秒的差异并不算什么。我能看到的最后一件事是输入更少,但是,我并不懒惰。

慕姐8265434

似乎没有return()它会更快...library(rbenchmark)x <- 1foo <- function(value) {&nbsp; return(value)}fuu <- function(value) {&nbsp; value}benchmark(foo(x),fuu(x),replications=1e7)&nbsp; &nbsp; test replications elapsed relative user.self sys.self user.child sys.child1 foo(x)&nbsp; &nbsp; &nbsp;10000000&nbsp; &nbsp;51.36 1.185322&nbsp; &nbsp; &nbsp;51.11&nbsp; &nbsp; &nbsp;0.11&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;02 fuu(x)&nbsp; &nbsp; &nbsp;10000000&nbsp; &nbsp;43.33 1.000000&nbsp; &nbsp; &nbsp;42.97&nbsp; &nbsp; &nbsp;0.05&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0____ 编辑__ _ __ _ __ _ __ __ _ __ _ ___我继续进行其他基准测试(benchmark(fuu(x),foo(x),replications=1e7)),结果相反...我将在服务器上尝试。
打开App,查看更多内容
随时随地看视频慕课网APP