[英]Can modern compilers optimize constant expressions where the expression is derived from a function?
[英]Compilers evaluating constant expressions
我希望我的编译器(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;
...
}
VS
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;
...
}
VS
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()
保证表达式仅计算一次,如果不在编译时,则在运行时 编译器会为每个编译器生成不同的代码吗,如果这样,那么哪个可以避免最多余的计算?
除非您尝试,否则无法确定编译器将执行的操作。 编译所有三个代码示例,然后查看生成的目标代码。
实际上,它们应该全部相同。 在编译器优化方面,恒定折叠大约是最低要求的结果。 如果您的编译器没有在编译时计算这些常量,则它不是优化的编译器。 除非你有一个很好的理由继续使用它,你应该把它搁进垃圾堆,找到一个不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.