Reputation: 448
Here is a data type I created to store a random amount of data. I've tested the object and it stores the data and is able to receive it (I've left out the functions that receive data since i don't think there relevant to the question)
class MyDynamicArrayV2
{
int* data;
int* tempArray;
int Position;
int Capacity;
void resize (int desiredSize)
{
delete data;
data = new int [desiredSize];
}
void copy (int* OrginalData,int* dataCopy, int OrginalData_length)
{
for (int i = 0; i < OrginalData_length; i++)
{
*(dataCopy+i) = *(OrginalData+i);
}
}
public :
MyDynamicArrayV2 ()
{
data = new int [2];
Position = 0;
Capacity = 2;
}
void AddData (double Num)
{
if ((Position+1)>Capacity)
{
tempArray = new int [(Capacity)+1]; //
copy(data,tempArray,Capacity); // Copy data to tempeoary storage
resize(Capacity*2);// Resizes the array
copy(tempArray,data,Capacity); // Restore data
Capacity= Capacity*2;
delete tempArray;
}
*(data+Position) = Num; // Allocates the data
Position++;
}
~MyDynamicArrayV2()
{
delete data;
}
};
I then tested the MyDynamicArray object against the Vector and list Container since these both are able to accept a random amount of data. I tested for speed using the following loop and for memory usage using task manager.
t1 = clock();
for (int i = 0 ; i <= 10000000; i++)
{
//MyDynamicArray.AddData(i);
//MyVector.push_back(i);
//Mylist.push_back(i);
}
t2 = clock();
double diff = (double)t2-(double)t1;
double seconds = diff/CLOCKS_PER_SEC;
cout << seconds;
Results. (MyArray: 0.473 seconds, 64.6 MB.) (MyVector: 3.595 seconds, 46.2 MB) (MyList: 16.987 seconds, 537.8 MB (What is the purpose of List??))
So my questions are how was the Vector class written? Why is my Object faster at allocating data compared to the Vector Object. Why is the vector object using less Memory than my Object?? And are you better of creating your own data type depending on the situation??
Side note: I also tested the speed at which my object and the vector object could access the data but they were both practically the same so i didn't add this test if anyone feels it is relevant please comment and i will add it.
Upvotes: 1
Views: 159
Reputation: 153955
For starters, you code is certainly wrong: you allocate arrays but you release objects! At the very least you need to use delete[] data;
. When testing your code against std::vector<double>
on MacOS with gcc and clang, std::vector<double>
consistently wins.
Did you compile with optimization? It is often quite deceptive to compile with debug mode: since std::vector<T>
is heavily factored template code, not inlining the code is rather harmful. Your code barely calls any other function, i.e., it wouldn't suffer, e.g., from function call overheads. Since it keep copying twice upon resizing the array while std::vector<T>
copy/moves just once in that case I'd expect std::vector<T>
to be faster (which it is for me when compiling with optimization).
Upvotes: 3