重载数组下标 [] 运算符很慢 [英] overloaded array subscript [] operator slow
问题描述
我用c++编写了自己的Array类并重载了数组下标[]操作符,代码:
I have written my own Array class in c++ and overloaded the array subscript [] operator, code:
inline dtype &operator[](const size_t i) { return _data[i]; }
inline dtype operator[](const size_t i) const { return _data[i];}
其中 _data 是指向包含数组的内存块的指针.分析表明,仅此重载运算符就占用了总计算时间的 10% 左右(在长时间的蒙特卡罗模拟中,我正在使用 g++ 进行最大优化进行编译).这似乎很多,知道这是为什么吗?
where _data is a pointer to the memory block containing the array. Profiling shows that this overloaded operator alone is taking about 10% of the overall computation time (on a long monte carlo simulation, and I am compiling using g++ with maximum optimization). This seems a lot, any idea why this is?
dtype是一个double,_data是一个指向double数组的指针
edited: dtype is a double, and _data is a pointer to an array of double
推荐答案
operator[]
的 const
重载实际上返回的是副本而不是 dtype常量&
.如果 dtype 很大,则副本可能很昂贵.
The const
overload of operator[]
is actually returning a copy instead of a dtype const &
. If dtype is big, the copy might be expensive.
像这样设计原型应该可以解决这个问题:
Prototyping it like that should solve that problem :
inline dtype const & operator[] (const size_t i) const { return _data[i]; }
这篇关于重载数组下标 [] 运算符很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!