什么时候是全球变量实际上认为好/推荐的做法? [英] When are global variables actually considered good/recommended practice?

查看:142
本文介绍了什么时候是全球变量实际上认为好/推荐的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读很多关于为什么全局变量是坏的,为什么不应该使用它们。但是大多数常用的编程语言以某种方式支持全局变量。

I've been reading a lot about why global variables are bad and why they should not be used. And yet most of the commonly used programming languages support globals in some way.

所以我的问题是什么是全局变量仍然需要的原因,它们提供一些独特的不能替代地实现的不可替代的优势?与用户指定的自定义间接方法相比,在全局寻址中是否有任何好处,可以从本地范围中检索对象?

So my question is what is the reason global variables are still needed, do they offer some unique and irreplaceable advantage that cannot be implemented alternatively? Are there any benefits to global addressing compared to user specified custom indirection to retrieve an object out of its local scope?

据我所知,在现代编程语言中,全局寻址与计算来自存储器地址的每个偏移相同的性能损失,无论它是从全局用户存储器的开始的偏移还是从这的偏移,或任何其他指针。因此,在性能方面,用户可以使用通用指针间接在所需的狭窄情况下伪造全局变量,而不会失去对真实全局变量的性能。还有什么?是否真的需要全局变量?

As far as I understand, in modern programming languages, global addressing comes with the same performance penalty as calculating every offset from a memory address, whether it is an offset from the beginning of the "global" user memory or an offset from a this or any other pointer. So in terms of performance, the user can fake globals in the narrow cases they are needed using common pointer indirection without losing performance to real global variables. So what else? Are global variables really needed?

推荐答案

全局变量通常不是坏的,因为它们的性能,它们使得很难封装一切 - 有信息泄漏,这往往使得很难弄清楚发生了什么。

Global variables aren't generally bad because of their performance, they're bad because in significantly sized programs, they make it hard to encapsulate everything - there's information "leakage" which can often make it very difficult to figure out what's going on.

基本上你的范围变量应该只是你的代码需要的工作和相对容易理解,没有更多。在打印十二次表的程序中有全局变量是可以管理的,在一个数百万行的会计程序中有它们并不是很好。

Basically the scope of your variables should be only what's required for your code to both work and be relatively easy to understand, and no more. Having global variables in a program which prints out the twelve-times tables is manageable, having them in a multi-million line accounting program is not so good.

这篇关于什么时候是全球变量实际上认为好/推荐的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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