0
这可能是一个初学者问题。性能对象属性与范围变量
阿
class A
{
private:
short* arrObject;
public:
A();
~A();
void func0();
};
A.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”
编辑:
另外,如果我改变阿成:
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
编译器,优化级别? – fghj
我不认为你在测量你认为你正在测量的东西。由于这个代码是非运算的,所以编译器最可能优化掉循环。 – NathanOliver
如果您正在优化某些内容,请务必检查反汇编。 – Drop