class MyClass {
private:
unsigned int currentTimeMS;
public:
void update() {
currentTimeMS = getTimeMS();
// ...
}
};
class MyClass {
public:
void update() {
unsigned int currentTimeMS = getTimeMS();
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
update()调用主游戏循环,所以在第二种情况下我们得到了很多分配操作(unsigned int currentTimeMS).在第一种情况下,我们只获得一个分配并使用之前分配的变量.哪个代码更好用,为什么?
我推荐第二个变体,因为它是无状态的,变量的范围更小.只有在您确实遇到性能问题时才使用第一个,我认为这不太可能.
如果以后不修改变量值,还应考虑使用它const来在代码中表达此意图并为编译器提供其他优化选项.