overloaded array subscript [] operator slow

寵の児 提交于 2021-02-08 14:02:23

问题


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

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?

edited: dtype is a double, and _data is a pointer to an array of double


回答1:


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


来源:https://stackoverflow.com/questions/22864368/overloaded-array-subscript-operator-slow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!