在C ++中i ++和++ i之间有性能差异吗? [英] Is there a performance difference between i++ and ++i in C++?

查看:101
本文介绍了在C ++中i ++和++ i之间有性能差异吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有这个问题 i ++ ++ i 之间有性能差异, code> in C

We have the question is there a performance difference between i++ and ++i in C?

C ++的答案是什么?

What's the answer for C++?

推荐答案

[执行摘要:如果您没有特定的理由使用<$ c,请使用 ++ i $ c> i ++ 。]

[Executive Summary: Use ++i if you don't have a specific reason to use i++.]

对于C ++,答案稍微复杂一些。

For C++, the answer is a bit more complicated.

如果 i 是一个简单类型(不是C ++类的实例),然后对C给出的答案(没有没有性能差异)保持,因为编译器正在生成代码。

If i is a simple type (not an instance of a C++ class), then the answer given for C ("No there is no performance difference") holds, since the compiler is generating the code.

如果 i 是C ++类的实例,则 i ++ ++ i 正在调用运算符++ 函数之一。以下是这些函数的标准对:

However, if i is an instance of a C++ class, then i++ and ++i are making calls to one of the operator++ functions. Here's a standard pair of these functions:

Foo& Foo::operator++()   // called for ++i
{
    this->data += 1;
    return *this;
}

Foo Foo::operator++(int ignored_dummy_value)   // called for i++
{
    Foo tmp(*this);   // variable "tmp" cannot be optimized away by the compiler
    ++(*this);
    return tmp;
}

由于编译器不是生成代码, $ c> operator ++ 函数,没有办法优化 tmp 变量及其关联的拷贝构造函数。如果复制构造函数很昂贵,那么这会对性能产生重大影响。

Since the compiler isn't generating code, but just calling an operator++ function, there is no way to optimize away the tmp variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact.

(感谢 Paul 查询C和C ++之间的区别。)

(Thanks to Paul for inquiring about the difference between C and C++.)

这篇关于在C ++中i ++和++ i之间有性能差异吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆