有类变量或局部函数变量更好/更快吗? [英] Is it better/faster to have class variables or local function variables?

查看:142
本文介绍了有类变量或局部函数变量更好/更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定我知道标题没有完全解释这个问题。所以我编写一个程序执行大量的计算,我试图优化它,以便它不会运行得这么慢。我有一个函数是一个类的成员,调用大约500万次。这是函数:

Ok I know the title doesn't fully explain this question. So I'm writing a program that performs a large number of calculations and I'm trying to optimize it so that it won't run quite so slow. I have a function that is a member of a class that gets called around 5 million times. This is the function:

void PointCamera::GetRay(float x, float y, Ray& out)
{
    //Find difference between location on view plane and origin and normalize
    float vpPointx = pixelSizex * (x - 0.5f * (float)width);
    float vpPointy = pixelSizey * (((float)height - y) - 0.5f * height);

    //Transform ray to camera's direction
    out.d = u * vpPointx + v * vpPointy - w * lens_distance;
    out.d.Normalize();

    //Set origin to camera location
    out.o = loc;
}



我想知道是否更好/更快地声明变量vpPointx和vpPointy在类中比每次我调用函数时声明它们。这是一个很好的优化,还是效果不大?

I'm wondering if it is better/faster to declare the variables vpPointx and vpPointy in the class than to declare them each time I call the function. Would this be a good optimization or would it have little effect?

一般来说,如果有什么东西可以优化,请让我知道。

And in general, if there is anything here that could be optimized please let me know.

推荐答案

通过限制变量的范围,您将给予编译器优化器更多的机会重新安排代码,使其运行更快。例如,它可以将这些变量的值完全保存在CPU寄存器中,这可能比存储器访问快一个数量级。此外,如果这些变量是类实例变量,那么编译器必须生成代码,以在每次访问它们时取消引用 this ,这很可能比局部变量访问。

By limiting the scope of your variables, you are giving more opportunity to the compiler optimiser to rearrange your code and make it run faster. For example, it might keep the values of those variables entirely within CPU registers, which may be an order of magnitude faster than memory access. Also, if those variables were class instance variables, then the compiler would have to generate code to dereference this every time you accessed them, which would very likely be slower than local variable access.

一如既往,你应该自己测量性能,并尝试代码两种方式(或更好,尽可能多的方式,你可以想到)。所有的优化建议都受你的编译器的影响,这需要实验。

As always, you should measure the performance yourself and try the code both ways (or better, as many ways as you can think of). All optimisation advice is subject to whatever your compiler actually does, which requires experimentation.

这篇关于有类变量或局部函数变量更好/更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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