更快地重用在公共作用域中定义的变量或在每个内部作用域中重新定义它?
具体来说,C++,如果它很重要的话,但我想答案就在汇编代码中。
如果我们在公共作用域(例如,函数)中有多个块,每个块都使用相同类型的变量,那么在公共作用域中定义变量并在每个块中重新初始化它,或者在每个块中重新定义并初始化它是更快吗?块的数量(或者没有根本的区别)?
例子: <代码>
int i;
{//block 1
i = SomeFunction();
...
}
{//block 2
i = SomeOtherFunction();
...
}
<代码> 相对 <代码>
{//block 1
int i = SomeFunction();
...
}
{//block 2
int i = SomeOtherFunction();
...
}
<代码>
C++ specifically, if it matters, but I imagine the answer lies in assembly code somehow.
If we have multiple blocks in a common scope (say, a function) which each use a variable of the same type, is it faster to define the variable in the common scope and reinitialise it in each block, or redefine and initialise it in each of the blocks (or is there no fundamental difference)?
Example:
int i;
{//block 1
i = SomeFunction();
...
}
{//block 2
i = SomeOtherFunction();
...
}
versus
{//block 1
int i = SomeFunction();
...
}
{//block 2
int i = SomeOtherFunction();
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果它不是结构/类,则基本上是相同的(尽管寄存器分配对于块内使用更明显不受限制,这可能有助于优化器,但任何需要该级别帮助的优化器都应该放入疗养院) 。
对于类来说,它取决于构造函数/析构函数和operator=()的相对性能。因此,没有单一的、正确的答案。尽管如此,一般而言,在更本地化的范围内创建变量是更好的编程实践,并且这种担忧通常会占主导地位。
It's basically the same if it's not a struct/class (though the register allocation is more obviously unconstrained for the intra-block usage which may help the optimiser, but any optimiser that needs that level of help ought to be put into a nursing home).
For classes, it depends on the relative performance of the constructor/destructor and operator=(). Therefore, there's no single, correct answer. Still, creating the variables inside a more localised scope is better programming practice in general, and this concern would usually dominate.
如果
i
是 POD 类型(如示例中所示的int
),则几乎肯定没有任何区别。如果 i 属于某种类型,具有不平凡的构造函数或赋值运算符,可以执行令人兴奋的操作,那么可能存在巨大差异,您必须比较适当的构造函数和赋值运算符的作用。如果输入了两个块,那么您还需要考虑析构函数。
一般来说,您不必担心。采用更简洁的方法,并在尽可能接近其首次使用的范围内声明变量,并且只有在分析器告诉您这是一个性能问题点时才将其重构。
If
i
is a POD type (like theint
shown in your example), there will almost certainly be no difference at all.If
i
is of some type that has a nontrivial constructor or an assignment operator that does something exciting, then there might be a huge difference and you'd have to compare what the appropriate constructors and assignment operators do. If both blocks are entered, then you'll need to consider the destructor as well.In general, you shouldn't worry about it. Take the cleaner approach and declare the variable in the most restricted scope possible, as close to its first use as possible, and only refactor it out if your profiler tells you it is a performance problem spot.
我猜大多数编译器都会为这两种情况和 int 生成相同的代码,但我个人更喜欢第二个选项,因为 i 处于尽可能小的范围内。
I would guess most compilers produce the same code for both cases and an
int
, but I personally prefer the second option sincei
is in the smallest possible scope.