premature optimization

博客展示了C++中`test`函数的代码,探讨了变量赋值与初始化的情况。对于简单类型如`double`、`float`,赋值和初始化差异不大,但对于有耗时构造函数的类,二者可能存在明显不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在性能上下面的二个函数有什么不同呢?哪个运行效率更高呢?

double test()
{
      double a,b,c;
      for(int i=0; i<n; i++){
          a = i*10;
          b = a-i;
          c += a*b;
       }
       return c;

}

or:

double test()
{
      double c;

      for(int i=0; i<n; i++){
          double a = i*10;
          double b = a-i;
          c += a*b;
       }
       return c;



Answer is : the later

consider if n == 0.  if n==0 for your second example the varibles would
never have to be allocated.

If they will always be allocated (n > 0) then the difference is assignment
.vs. initialization.  For simple types (double, float, etc...) it probably
doesn't make much difference.  For classes, however, it can if they have
constructors that take time.

The general rule in C++ is delcare varaibles just before you use them.  One
of the main reasons is so you know what the variable is declared.  If a
function is large and you come across
a = 10;
what is a?  Is it int?  double?  char?  a class?  You'd have to scroll up to
the top of the function to find out.  However
double a = 10;
makes it easier to read/maintain the code IMO.





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值