正在访问 c++成员类通过“this->member”比对“member”的隐式调用更快/更慢
在我们的朋友谷歌上进行一番搜索后,我无法得到以下观点的明确看法。
我习惯用 this->
来调用类成员。即使不需要,我发现它更明确,因为它在维护一些带有大量变量的繁重算法时很有帮助。
当我正在研究一种应该优化的算法时,我想知道使用 this->
是否会改变运行时性能。
是吗?
After some searching on our friend google, I could not get a clear view on the following point.
I'm used to call class members with this->
. Even if not needed, I find it more explicit as it helps when maintaining some heavy piece of algorithm with loads of vars.
As I'm working on a supposed-to-be-optimised algorithm, I was wondering whether using this->
would alter runtime performance or not.
Does it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,这两种情况下的调用完全相同。
No, the call is exactly the same in both cases.
这没有什么区别。这是 GCC 的演示。来源是简单的类,但为了清楚起见,我将这篇文章限制为差异。
It doesn't make any difference. Here's a demonstration with GCC. The source is simple class, but I've restricted this post to the difference for clarity.
zennehoy 已经给出了答案,这里是一个简单测试类的汇编代码(由 Microsoft C++ 编译器生成):
Visual Studio 中的反汇编窗口显示两个函数的汇编代码是相同的:
并且 main 中的代码:
Microsoft 编译器使用 <类成员调用默认使用 code>__thiscall 调用约定,并且
this
指针通过 ECX 寄存器传递。Answer has been given by zennehoy and here's assembly code (generated by Microsoft C++ compiler) for a simple test class:
Disassembly Window in Visual Studio shows that assembly code is the same for both functions:
And the code in the main:
Microsoft compiler uses
__thiscall
calling convention by default for class member calls andthis
pointer is passed via ECX register.语言的编译涉及多个层。
访问
member
作为member
、this->member
、MyClass::member
等之间的区别...是句法差异。更准确地说,这是一个名称查找的问题,以及编译器的前端如何“找到”您所引用的确切元素。因此,您可以通过更精确来加速编译...尽管这不会引起注意(C++ 中涉及更多耗时的任务,例如打开所有这些包含)。
由于(在本例中)您引用的是同一元素,因此它应该无关紧要。
现在,解释性语言可以进行有趣的类比。在解释性语言中,名称查找将延迟到调用该行(或函数)的那一刻。因此,它可能会在运行时产生影响(尽管同样可能并不明显)。
There are several layers involved in the compilation of a language.
The difference between accessing
member
asmember
,this->member
,MyClass::member
etc... is a syntactic difference.More precisely, it's a matter of name lookup, and how the front-end of the compiler will "find" the exact element you are referring to. Therefore, you might speed up compilation by being more precise... though it will be unnoticeable (there are much more time-consuming tasks involved in C++, like opening all those includes).
Since (in this case) you are referring to the same element, it should not matter.
Now, an interesting parallel can be done with interpreted languages. In an interpreted language, the name lookup will be delayed to the moment where the line (or function) is called. Therefore, it could have an impact at runtime (though once again, probably not really noticeable).