问题
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