使用全局会产生任何开销吗? [英] Does using global create any overhead?

查看:84
本文介绍了使用全局会产生任何开销吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果对不使用的变量使用global关键字是否会出现问题?比较:

Is it a problem if you use the global keyword on variables you don't end up using? Compare:

function foo() {
    global $fu;
    global $bah;
    if (something()) {
        $fu->doSomething();
    } else {
        $bah->doSomething();
    }
}

function bar() {
    if (something()) {
        global $fu;
        $fu->doSomething();
    } else {
        global $bah;
        $bah->doSomething();
    }
}

我很清楚,使用第二种方法会使维护此代码更加困难,并且通常首选将所有全局变量放在函数的开头,因此:忽略可维护性和代码样式上的差异这两个功能中,两者在开销方面有区别吗?

I'm quite aware that using the second method makes maintaining this code much harder, and that it's generally preferred to put all your globals at the start of functions, so: Ignoring the difference in maintainability and code-styling of the two functions, is there a difference between these two in terms of overhead?

推荐答案

如果存在,将无法(人工)进行测量,除非您实际上要调用此函数数百万次.即使这是具有该属性的递归函数,我仍然不会将第二种方法用于已经提到的可维护性方面.

If there is, it won't be (humanly) measurable, unless you are literally calling this function millions of times. And even if it was a recursive function with that property, I still wouldn't use your second method for the maintainability aspects you already brought up.

为了争辩,我实际上去做基准测试,bar()在一百万次调用中以0.1s的速度慢了下来.这意味着性能是明智的,您仍然有理由使用更干净的版本.

For arguments sake, I actually went and benchmarked this, and bar() ended up slower by 0.1s over one million calls. Which means performance wise, you still have a reason to use the cleaner version.

这篇关于使用全局会产生任何开销吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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