作者:朱泊潇 | 来源:互联网 | 2023-02-01 22:03
Ihaverecentlylearnedthatifyouhaveareferencetoaclassasafunctionparameter,itisbette
I have recently learned that if you have a reference to a class as a function parameter, it is better practice and more efficient to store certain needed pieces of information as local variables rather than accessing the classes members every time you need them in the function.
我最近了解到,如果你有一个类作为函数参数的引用,那么将某些所需的信息作为局部变量存储,而不是每次在函数中需要时访问类成员都是更好的实践和更有效的方法。
so...
void function(const Sphere& s)
{
//lots of calls to s.centre and s.radius
}
or
void function(const Sphere& s)
{
Vector3 centre = s.centre; float radius = s.radius;
//an equal amount of calls to centre and radius
}
I am told the second is better, but why? And also, where is a good place to start researching this more fully? (for dummys please!)
我被告知第二个更好,但为什么?而且,哪里有一个开始更充分地研究这个的好地方? (请给dummys!)
6 个解决方案
2
Here is a general outlook of your code:
以下是您的代码的一般展望:
void function(Sphere s)
{
Vector3 centre = s.centre; float radius = s.radius;
//an equal amount of calls to centre and radius
}
First off, you'd gain much more efficiency by passing Sphere
as a const
reference. This way, a new copy isn't created, which is probably more expensive than member access. So the way to go is:
首先,通过将Sphere作为const引用传递,您将获得更高的效率。这样,不会创建新副本,这可能比成员访问更昂贵。所以要走的路是:
void function(const Sphere& s)
{
Vector3 centre = s.centre; float radius = s.radius;
//an equal amount of calls to centre and radius
}
Secondly, you shouldn't access members of classes directly. It may be easy now, but in a large project it's really hard to debug. You should use inline getters and setters. That way, the generated code is the same, but you have a single entry point.
其次,您不应该直接访问类的成员。现在可能很容易,但在大型项目中,调试真的很难。您应该使用内联getter和setter。这样,生成的代码是相同的,但您只有一个入口点。
Thirdly, this version isn't thread safe. What if a different thread changes s
? s.center
and s.radius
would change, but you'd still be operating on the old values.
第三,这个版本不是线程安全的。如果另一个线程改变了怎么办? s.center和s.radius会改变,但你仍然会使用旧值。
Lastly, compilers do a better job at optimizing than you can, so it's better to leave this one up to the compiler.
最后,编译器在优化方面做得比你做得更好,所以最好把这个放到编译器上。