Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloaded array subscript [] operator slow

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

like image 752
stefano Avatar asked Apr 04 '14 13:04

stefano


People also ask

How can subscript operator be overloaded?

The subscript operator [] is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays.

How do you overload double subscripts in C++?

There isn't a double-subscript operator in C++. What you can do is overload operator[] to return an object that also overloads operator[] . This will enable you to write m[i][j] .

What are the pitfalls of operator overloading in C++?

The ^ operator is weaker than + (but stronger than <<). Moral: You cannot change the operator precedence when overloading operators. Do not overload an operator if its precedence is not intuitive for the problem domain. The precedence of ^ is fine for XOR but not for raising to a power.

How do you overload the index operator C++?

In order to overload the operator of indexing the elements of the array [], the operator function operator[]() must be implemented in the class. There are 2 ways to implement the operator function operator[](). These variants differ in returning a value from an operator function.


1 Answers

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]; }
like image 158
Chnossos Avatar answered Oct 07 '22 20:10

Chnossos