简体   繁体   English

性能:重载[]和对函数的调用

[英]Performance: Overloaded [] and a call to a function

My initial thought over the performance of calling an over loaded [] to acquire a member data and calling a function like getData(index) would be the same. 我对调用overload []获取成员数据和调用类似getData(index)之类的性能的最初想法是相同的。 Since calling [] is essentially a function call. 由于调用[]本质上是函数调用。 Assume they acquire the same data like values[1] and values.getData(1) would return the same value. 假设它们获取相同的数据,如values [1]和values.getData(1)将返回相同的值。 Am I wrong? 我错了吗? If they perform the same, is there a non-performance advantage to using [] in this case? 如果它们执行相同的操作,则在这种情况下使用[]有非性能优势吗?

They are the same, under the hood. 它们在引擎盖下是相同的。 Overloaded operators are just a unique syntax for a function call. 重载运算符只是函数调用的唯一语法。 The only thing changing is the appearance of code that calls it. 唯一改变的是调用它的代码的外观。

You're even allowed to force the operator calls to look function-like. 您甚至可以强制操作员调用看起来像函数。

values[1]

may also be written as 也可以写成

values.operator[]( 1 )
//     ^^^^^^^^^^ This is effectively the name of your function.

Both are the same thing, as you also mention in your question. 正如您在问题中也提到的那样,两者都是同一回事。 Overloads are just function calls. 重载只是函数调用。 No performance gain. 没有性能提升。

However, operator[] historically means that (or is expected to have) there is a contiguous formation of internal data representation in the memory, or more generally serve as an index to container like data structures. 但是, operator[]历史上意味着(或预期具有)内存中内部数据表示形式的连续形成,或更普遍地,它用作类似于容器的数据结构的索引。 Thus, it is generally implemented in classes like vectors, arrays, matrices, etc. 因此,通常在矢量,数组,矩阵等类中实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM