Search code examples
c++vectorprocessing-efficiency

Making a vector more efficient while adding elements


I am thinking of making the vector data structure more efficient.

Suppose it is for some generic data type T...then while adding a new element to the vector, what the current std::vector does is to reallocate a whole new memory chunk of n+1 elements.

What I want to do...

I wrote a small program :

#include<iostream>

using namespace std;

int main ()
{

    int *i,*j;
    i=new int;
    cout<<i;
    delete i;
    j=new int ;
    cout<<j;
    delete j;

        return 0;
}

Both Memory Locations were The Same...

Now What i am thinking is that first i will allocate memory for the generic data type like this :

T *temp=new T;

Now Compare the memory address of temp to the address of last element of the vector....If they differ by sizeof (T) then i will add the new element there itself....else do it the way std::vector does it....

So It reduces the cost of copying all the elements...if the data is large then this can make a significant difference......!!

Pls tell me if i am on the right track...


Solution

  • I understand your idea as

    If new gives me back an address which is contiguous with the memory already held by the MyVector object, I will just use it without reallocating.

    Yes, this could indeed work in theory. However, in practice, it's impossible to obtain such a contiguous address, because the allocator will most likely store some internal data at the start of the block it allocates (such as its size, or a pointer to the next block, or whatever).

    Exact details depend on the allocator used by your standard library (and eventuall OS), but here's an example of typical behaviour. You call new T where sizeof(T) is 16 (for example). operator new calls malloc internally, which calls your OS's allocation function. That function allocates 20 bytes of memory at address X. It stores "16" in the first 4 bytes at X, and returns the address X + 4 to malloc, which in turn returns it to operator new and that to your application. So there's no way you'll ever get contiguous memory.