Getters和Setter。是否有性能开销? [英] Getters and Setters. Is there performance overhead?

查看:147
本文介绍了Getters和Setter。是否有性能开销?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C ++项目中有一个粒子系统引擎,粒子本身只是没有函数的变量的结构。目前,每个粒子(粒子)通过直接访问它的变量从它的父类(ParticleSystem)更新。例如

I have a Particle System Engine in my C++ project and the particles themselves are just structs of variables with no functions. Currently, each particle (Particle) is updated from its parent class (ParticleSystem) by having its variables accessed directly. E.g.

particle.x += particle.vx;

但我使用getters和setter进行辩论,如下所示:

I am however, debating using getters and setters like this:

particle.setX(particle.getX()+ particle.getVX());

我的问题是:调用getter和setter是否有任何性能开销,而不是直接的数据访问?

毕竟,有很多很多粒子要更新...

After all, I do have many many particles to update through...

推荐答案

Setters和getters有一个性能开销他们几乎总是优化的编译器,做链接时间优化。而对于不编译器,如果他们知道函数体(即不只是一个原型),它将被优化。

Setters and getters have a performance overhead when not optimized out. They are almost always optimized out on compilers that do link time optimization. And on compilers that do not, if they have knowledge of the function body (ie not just a prototype) it will be optimized out.

但是,使用getter和setter是因为你可能想要获得或设置该变量有额外的副作用。类似于改变对象的位置也改变了物理模拟中的附近对象的位置等。

However, you use getters and setters are there because you might want getting or setting that variable to have additional side effects. Like changing the position of an object also changes the position of nearby objects in a physics simulation or some such.

最后,在一个getter和setter操作的开销上下文优化的代码,非常小,不值得担心,除非代码很热。如果它很热,很简单只是移动getter或setter到头文件和内联。

Finally, the overhead of a getter and setter operation, within the context of optimized code, is very small, not worth worrying about unless the code is hot. And if it's hot, it's SO EASY to just move the getter or setter to the header file and inline it.

所以总结一下,getter和setter是非常值得的次要或不存在的开销,因为它允许你非常明确地指定什么可以和不能发生与您的对象,它还允许您编组的任何更改。

So to sum up, getters and setters are well worth the minor or non-existent overhead, as it allows you to specify very specifically what can and cannot happen with your object, and it also allows you to marshal any changes.

这篇关于Getters和Setter。是否有性能开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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