挑剔:Tcl 是否存储在变量中,为了速度,在过程中 [英] Nitpicking: Tcl storing in a variable or not, for speed, in procedures

查看:69
本文介绍了挑剔:Tcl 是否存储在变量中,为了速度,在过程中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个普遍的问题.假设 TCL 8.6,让我们假设我有一个相当短的程序.我有两种返回感兴趣值的方法:
1. 使用一些标准做法 if/else 代码,存储在变量中,并返回变量的值.例如:

This is something of a general question. Assuming TCL 8.6, let's ay that I have a rather short procedure. I have 2 ways of returning the value of interest:
1. use some standard practice if/else code, store in a variable, and return the variable's value. For example:

proc me { gop goo } {
   if { [ lomsa $gop ] {
      set ret [ foo $goo $gop ]
   } else {
      set ret [ bar $gop $goo ]
   }
   return $ret
}

2.使用三元参数,并且基本上没有添加私有变量的过程(即只使用参数).三元表达式的输出是返回值.例如:

2. use the ternary argument, and basically, have the procedure no added private variable (that is, only the arguments are used). The output of ternary expression is what returns the value. For example:

proc me { gop goo } {
   expr { [ lomsa $gop ] ? [ foo $goo $gop ] : [ bar $gop $goo ] }
}

我团队的一些成员认为可读性在第 1 项中略好一些.
我无法在我的 TCL 设置中访问伪代码引擎(它是来自供应商的一个 shell),但我认为代码中的差异及其性能将是,但只是轻微的,如果有的话.即,该过程需要将返回的值存储在某处.为它注册一个特定变量的成本是多少,而只是将其作为返回值保留?
这个问题可以扩展,例如,对于 switch 语句.相同的规则适用.switch 语句可以存储在一个变量中,然后,在 switch 之后,返回变量的值,或者 switch 语句将只返回该值,而无需将其存储在变量中.此外,在返回部分之前可能有大量代码.上面列出的过程就是他们所说的便利过程"
您可以假设代码的性能非常重要.

Readability is considered by some members of my team to be better slightly better in item 1.
I can't access the pseudo code engine in my TCL setup (it is a shell from a vendor), but I assume that difference in the code, and its' performance will be, but only slight, if at all. I.e., the procedure needs to store the value returned somewhere. How much is the cost of registering a specific variable for it, vs. just keeping it as a return value?
The question can be extended, for example, for switch statements. Same rules apply. The switch statement can store in a variable, and then, after the switch, the variable's value is returned, or the switch statement will just return the value, w/o storing it in a variable. Also, there can be extensive code prior to the return part of it. The listed above procedure is what they call a "convenience procedure"
You can assume that performance is of high interest for the code.

推荐答案

除了可读性之外,三元运算符可能会产生意想不到的结果.例如,如果选定的 proc 返回 0123,则您的 me proc 将返回 83.因此,除非您确定这种情况永远不会发生,否则使用 if 命令会更安全.

Aside from readability, the ternary operator may produce unexpected results. For example, if the selected proc returns 0123, your me proc will return 83 instead. So unless you are sure that situation can never occur, it's safer to use the if command.

这篇关于挑剔:Tcl 是否存储在变量中,为了速度,在过程中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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