Shrinkable arrays vs vectors

The C++ standard containers implementations, such as vector, map, list, and others are very useful.

Sometimes, when a better performance is needed, these implementations may be discarded by the programmer, because it is possible to manage faster the data with native arrays or with own container implementations.

The performance offered by std::vector when shrinking may be overcome, because std::allocator doesn't support in-place reallocation.

Every time that std::vector::shrink_to_fit is called, it will allocate a block with the new size, copy the useful data and delete the old block.

We've tested this code in a personal computer and obtained 100 times better performance with in-place shrinkable arrays than with vectors.

Sometimes it is also easier to handle multidimensional arrays using the new[] and delete[] operators than with vectors of pointers or vectors of vectors.

(1 thread, GNU Compiler, -O0 flag, Intel Core i7-3rd 2.1GHz, DDR3-1600)





/* author: ncomputers.org */
#include<cstdlib>
#include<iostream>
#include<time.h>
#include<vector>
using namespace std;

struct A{
    int a;
    A():a(rand()){}
};

void*operator new[](size_t s){
    return malloc(s);
}
void operator delete[](void*p){
    free(p);
}
void operator delete[](void*p,size_t s){
    if(realloc(p,s)!=p)throw 0;
}

int main(){
    unsigned int a=0,v=0,s,S=1024,z=time(0)+1;
    while(time(0)<z);
    z++;
    A*b;
    while(time(0)<z){
        b=new A[S]();
        //Suggested syntax:
        //delete[1]b;
        for(s=S-1;s>0;--s)operator delete[](b,s*sizeof(A));
        delete[]b;
        a++;
    }
    z++;
    vector<A>*c;
    while(time(0)<z){
        c=new vector<A>(S);
        for(s=S-1;s>0;--s){
            c->resize(s);
            //C++11
            c->shrink_to_fit();
        }
        delete c;
        v++;
    }
    cout<<"Total arrays: "<<a<<endl;
    cout<<"Total vector: "<<v<<endl;
    return 0;
}