性能对象属性与范围变量

Performance object properties vs scope variables

本文关键字:范围 变量 属性 对象 性能      更新时间:2023-10-16

这可能是一个初学者的问题。

class A
{
private:
    short* arrObject;
public:
    A();
    ~A();
    void func0();
};

答.cpp

#include "A.h"
#include "Timer.h"
#include <iostream>
using namespace std;
A::A()
{
    arrObject = new short[4];
}

A::~A()
{
}

void A::func0() {
    Timer timer; // this class measures time in seconds
    short* arrScope = new short[4];
    timer.start();
    for (int i = 0; i < 1000000; i++)
    {
        arrScope[3] = 987;
    }
    cout << "Writing in scope array " << timer.end() << endl;
    timer.start();
    for (int i = 0; i < 1000000; i++)
    {
        arrObject[3] = 987;
    }
    cout << "Writing in object array " << timer.end() << endl;
    cout << endl;
}

A 实例上调用 func0 会生成输出:

Writing in scope array 0
Writing in object array 0.000771421

这意味着使用对象属性比使用范围变量慢。为什么会这样?

我使用的是Visual Studio 2013,所以它是Microsoft C/C++编译器。优化在VS中选择为"最大化速度/O2"

编辑:

此外,如果我将 A.h 更改为:

class A
{
private:
    short arrObject[4];
public:
    A();
    ~A();
    void func0();
};

并丢失 A.cpp 中构造的初始化,差异消失,输出为:

Writing to scope array 0
Writing to object array 3.31082-007

好的,是的,这是优化的事情。

如果我禁用所有优化,两个计时器都会显示确切的时间。另外,如果我保持优化并稍微弄乱代码:

void A::func0() {
    Timer timer;
    short* arrScope = new short[4];
    timer.start();
    for (int i = 0; i < 1000000; i++)
    {
        arrScope[i % 4] = i;
    }
    cout << "Writing in scope array " << timer.end() << endl;
    timer.start();
    for (int i = 0; i < 1000000; i++)
    {
        arrObject[i%4] = i;
    }
    cout << "Writing in object array " << timer.end() << endl;

    cout << endl;
}

计时器也显示相同的时间。

Run #1: 0.00263972 / 0.00267415
Run #2: 0.00069362 / 0.00099159
Run #3: 0.00251192 / 0.00250728