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

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

问题描述

我们有一个问题 i++++i 在 C 中是否有性能差异强>?

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

C++ 的答案是什么?

What's the answer for C++?

推荐答案

[执行摘要:如果您没有特定原因使用 i++,请使用 ++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 正在调用 i++i 之一代码>operator++ 函数.这是这些函数的标准对:

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;
}

由于编译器不生成代码,而只是调用 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.

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

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