C/C++性能全局与获取/设置方法

I saw this question asking about whether globals are bad.

As I thought about the ramifications of it, the only argument I could come up with that they're necessary in some cases might be for performance reasons.

But, I'm not really sure about that. So my question is, would using a global be faster than using a get/set method call?

#0

A good modern compiler should inline the get/set method calls such that there's probably no real difference.

In almost any case it's much more important to worry about whether statics/globals are going to cause you a headache than the performance implications, which are going to be nearly undetectable anyway.

#1

You could gain more performance yet by writing in assembler. And also lose more time in debugging your code.

It's exactly the same type of trade.

#2

A more appropriate comparison would be between accessing a global (a static) and a local.

Indeed a global is faster because accessing a local requires the variable offset to be added to the value of the stack pointer.

However, you will never, ever need to worry about this. Try concentrating on things that matter, such as making your code be readable, writable, and working.

#3

It might be slightly faster, but not a huge increase in speed. Globals over having getter and setter functions for everything does keep application size down though. Whether this type of size savings is beneficial to your application is relevant to the platform you are targeting. For instance, when developing embedded applications, platforms with limited memory, it can be a viable solution.

#4

It depends on the CPU and compiler. On at least one popular PPC chipset, loading a global variable requires extra instructions because it cannot be encoded in a 16-bit relative offset.

Plus, it can take a giant crap on cache locality and/or destroy any optimizations that assume no aliasing. Assuming that globals can increase performance is somewhat naive.

推荐文章

是否有C#的设置比较操作?

是否有C#的设置比较操作?

推荐文章

没有为文本框启动asp.net自定义验证程序

没有为文本框启动asp.net自定义验证程序

推荐文章

双击文本使其可复制

双击文本使其可复制

推荐文章

为自动化测试捕获浏览器JS控制台输出

为自动化测试捕获浏览器JS控制台输出

推荐文章

UITextView在键入时隐藏文本

UITextView在键入时隐藏文本

推荐文章

LinQ字体大小显示问题

LinQ字体大小显示问题

推荐文章

利用SQL Server实现逆向地理编码

利用SQL Server实现逆向地理编码

推荐文章

Pchart-从MySQL检索数据

Pchart-从MySQL检索数据

推荐文章

如何将不同的后端解决方案连接到通用API中?

如何将不同的后端解决方案连接到通用API中?

推荐文章

通过浏览器记录http表单帖子

通过浏览器记录http表单帖子

推荐文章

JAXB在java 1.6u03与java1.6.0u13及以上版本中的比较

JAXB在java 1.6u03与java1.6.0u13及以上版本中的比较

推荐文章

JQuery ScrollTo冲突

JQuery ScrollTo冲突

推荐文章

如何将字节数组写入process builder(Java)的OutputStream

如何将字节数组写入process builder(Java)的OutputStream

推荐文章

阈值在Log4J中是什么意思?

阈值在Log4J中是什么意思?

推荐文章

如何在java中将文件位置作为参数传递

如何在java中将文件位置作为参数传递

推荐文章

将资源目录导入JNLP?

将资源目录导入JNLP?