[英]Keeping a reference to the object itself inside member functions
在节省时间和减少操作数量方面,在经常使用this->
的成员函数的开头创建对(*this)
的引用是否有用? 编译器(gcc最让我感兴趣)已经为我优化了吗? 有没有理由不这样做?
例:
void A::checkBytes( const byte * dataChunk, uint32_t chunkSize )
{
A & self = (*this);
bool UTF8Valid = self.InvalidSequences & 1;
byte current, expectedUTF8Bytes = 0;
for (uint32_t i = 0; i < chunkSize; i++)
{
current = dataChunk[i];
// many tests with 'current' and 'this->InvalidSequences'
self.Count[current]++;
self.ChunkSize++;
}
if (!UTF8Valid) self.InvalidSequences |= 1;
}
我知道每个非静态成员函数都有其自己的this
。 我知道我会同时拥有隐藏的A * this
和A & self
。 我不知道很多this->someMember
是否会比许多referenceToThis.someMember
花费更多。
不,最坏的情况是它会占用额外的堆栈空间并需要一些额外的指令,最理想的情况是它会优化回到this->
。
this
几乎肯定会存在于寄存器中,并且像A&
这样的引用基本上是实现级别的指针。
尝试存储指向this->Count
等的直接指针/引用可能甚至没有收益,因为在大多数平台上, this->Count[n]
可以是一条指令(例如,在x86上,我相信LEA
将是如果使用过,则可能需要检查反汇编)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.