Thank you all of you for your time, your comments and your help.
I'll answer first some of your comments and then I'll add information about this topic.
NT3:
You aren't allocating 'groups of 100 vectors' or 'groups of 100 arrays' - you are allocating one with 100 elements. So your results are 100 times as large as they should be. |
Yes, it is true.
Also, you have a memory leak. When you are allocating an array with the new[] operator, you need to use delete[] operator to clean up. |
It is true. On this case does that mistake probably give the same results. (GNU Compiler -O3 flag)
Cire:
You're not even doing equivalent things. There is no need for new/delete in the vector loop. |
One of our codes requires an undefined number of arrays or vectors. Each array or vector "lives" for a variable amount of time until it "dies".
One wonders if the OP is aware of the shrink_to_fit methods on some standard containers, notably std::deque and std::vector. |
So far we've researched, to shrink an array could be faster than to shrink a vector.
Duoas:
Directly allocating an manipulating an array is faster than using vectors (for small n)
true |
This could be a third reason to suggest standard shrinkable arrays.
Check out this sweet language modification idea: allow resizing of allocated arrays.
a common want (but not strictly necessary) |
Yes, it is a sweet language modification. It is possible, that I use wrong the shrink word. My English has mistakes! For shrinkable arrays I understand, arrays, which can be resized only to a minor size.
Additional information:
I've updated and published content on our website about this topic:
http://ncomputers.org/content/code.php?src=suggestions/shrink%20arrays%20cpp
We've two good reasons to suggest these shrinkable arrays, we're looking for a third, which could be what
Duoas wrote:
Directly allocating an manipulating an array is faster than using vectors (for small n)
true |
The more good reasons it has, the stronger it is.
Performance is the main reason:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
#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]();
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;
}
|
Thank you very much!
Best regards,
http://ncomputers.org/
(On Oct 9 I've edited this post, to express better my answers to your comments)