从函数返回值时的效率问题 [英] Returning values from functions when efficiency matters

查看:118
本文介绍了从函数返回值时的效率问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,有几种方法可以从bash函数返回一个值。

It seems to me, there are several ways to return a value from a Bash function.

方法1 :使用局部全局变量,它被定义为本地在来电者:

Approach 1: Use a "local-global" variable, which is defined as local in the caller:

func1() {
    a=10
}

parent1() {
    local a

    func1
    a=$(($a + 1))
}

方法2 :使用命令替换:

func2() {
    echo 10
}

parent2() {
    a=$(func2)
    a=$(($a + 1))
}

有一个

多大的加速可以使用方法1在approach2期待?

How much speedup could one expect from using approach 1 over approach2?

和,我知道这是不是良好的编程习惯使用全局变量像方法1,但它可能在某些时候,由于效率的考虑是合理的?

And, I know that it is not good programming practice to use global variables like in approach 1, but could it at some point be justified due to efficiency considerations?

推荐答案

在shell脚本中最昂贵的操作分叉。任何涉及操作叉,如命令替换,将幅度超过一慢1-3个数量是没有。

The single most expensive operation in shell scripting is forking. Any operation involving a fork, such as command substitution, will be 1-3 orders of magnitude slower than one that doesn't.

例如,下面是一个循环,读了一堆生成的文件文件-1234 的窗体上的直接的方法,并剥离该文件 - preFIX使用 SED ,共需三个叉(命令替换+两级流水线):

For example, here's a straight forward approach for a loop that reads a bunch of generated files on the form of file-1234 and strips out the file- prefix using sed, requiring a total of three forks (command substitution + two stage pipeline):

$ time printf "file-%s\n" {1..10000} |
     while read line; do n=$(echo "$line" | sed -e "s/.*-//"); done

real    0m46.847s

下面是一个循环,做同样的事情与参数扩展,无需叉:

Here's a loop that does the same thing with parameter expansion, requiring no forks:

$ time printf "file-%s\n" {1..10000} |
     while read line; do n=${line#*-}; done

real    0m0.150s

该版本的forky 300X花费更长的时间。

The forky version takes 300x longer.

所以,回答你的问题是肯定的:如果效率的问题,你有分解出或更换的forky code坚实的理由。

Therefore, the answer to your question is yes: if efficiency matters, you have solid justification for factoring out or replacing forky code.

在交岔路口数量是恒定的相对于输入(或它是太乱了,使之常数),和code仍然太慢,这时候你应该以更快的语言重写。

When the fork count is constant with respect to the input (or it's too messy to make it constant), and the code is still too slow, that's when you should rewrite it in a faster language.

这篇关于从函数返回值时的效率问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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