我希望我的编译器(VS 2013)避免任何多余的算术计算,最好是在编译时计算一次以下内容。
基本上我看到三种情况如下:
例如:
void Mesh::Draw1()
{
const static uint32_t gStaticOffset = 0;
const static uint32_t gVertexSize = sizeof(float) * 3;
const static uint32_t gBoneIndexSize = sizeof(uint32_t) * MAX_BONES;
const static uint32_t gBoneWeightSize = sizeof(float) * MAX_BONES;
...
}
与
void Mesh::Draw2()
{
const uint32_t staticOffset = 0;
const uint32_t vertexSize = sizeof(float) * 3;
const uint32_t boneIndexSize = sizeof(uint32_t) * MAX_BONES;
const uint32_t boneWeightSize = sizeof(float) * MAX_BONES;
...
}
与
const static uint32_t gStaticOffset = 0;
const static uint32_t gVertexSize = sizeof(float) * 3;
const static uint32_t gBoneIndexSize = sizeof(uint32_t) * MAX_BONES;
const static uint32_t gBoneWeightSize = sizeof(float) * MAX_BONES;
void Mesh::Draw3()
{
...
}
我的想法,如果错了,请纠正我:
-
Draw1()
可能会重新计算每个函数调用的本地表达式取决于编译器 -
Draw2()
和Draw3()
保证表达式只会计算一次,如果不在编译时,则在运行时 - 三种变体的任何表达式是否为编译时计算完全取决于编译器
编译器是否会为每个代码生成不同的代码,如果是,哪一个可以避免最多的冗余计算?
除非您尝试,否则无法确定编译器将执行什么操作。编译所有三个代码示例,然后查看生成的对象代码。
实际上,它们都应该是相同的。在编译器优化方面,常量折叠大约是最低的唾手可得的果实。如果编译器未在编译时计算这些常量,则它不是优化编译器。除非您有很好的理由继续使用它,否则您应该将其放入垃圾堆并找到另一个。