I am experiencing unexpected performance degradation when using vectors with classes.
I have a csv_File class that reads in a csv file and stores the contents in a 2D vector. There’s a member function that allows access, e.g.
csv_File file("file.csv");
file.access(2,2);
To access the 2,2 element.
Then, I have another class csv_Array that stores multiple csv_File objects in a vector, e.g private member vector
There’s a member function that allows access, i.e. it returns a csv_File object, for example:
csv_Array file_array(5); //store 5 csv_File objects
file_array.grab(0).access(2,2);
In the second line, grab returns a csv_File object (in this case, the first one) and access is a member function of the csv_File object.
However, I have noticed that the call
csv_Array.grab(0).access(2,2);
is much slower than it should be (it should be just 3 vector::at calls).
Is there some sort of hidden copy going on that is making this very slow?
EDIT: Here are some of the relevant function prototypes:
//Access in csv_File
std::string access(int row, int column);
//grab in csv_Array and csv_Analysis (mentioned below)
csv_File grab(int index);
ADDITIONAL DETAILS (if necessary):
The application of this code is to load a bunch of csv files into memory before passing it to a friend class that will do some calculations with the data. Schematically, I have the following:
1) csv_Array has private member vector storage;
2) csv_Analysis is a class that is a friend of csv_Array
3) csv_Analysis accesses vector storage, which is in csv_Array
4) This access is done by passing csv_Analysis a reference to storage in csv_Array (so no copy hopefully….), e.g
public:
csv_Analysis(csv_Array &csv_block);
Thus, the call given above[file_array.grab(0).access(2,2); ]
actually has one additional class “level” in between and is more like
csv_Analysis analysis_Object(file_array);
analysis_Object.grab(0).access(2,2);
where grab acts in the same way, and is also defined as a member function of csv_Analysis class.
You probably want to make
grabreturn a reference rather than a copy: