Suppose I already know the size of the array to be created.Let it be N.
int A[N];
int *A = new int[N];
Which way is better/fast ? Why ?
Suppose I already know the size of the array to be created.Let it be N.
int A[N];
int *A = new int[N];
Which way is better/fast ? Why ?
int a[N];
If N
is not a constexpr
, this is only legal under certain compilers, usually with language extensions enabled, or a C++14 compiler. ("Variable Length Arrays")
Note this is considered "C syntax" and the modern, preferred way to do this is:
std::array<int, N> a;
This creates an array of N
integers on the stack. If N * sizeof(int)
is >= the remaining stack size, you may have a problem.
However: because it is a local object, it has automatic lifetime - it will go away when a
goes out of scope. Allocating memory on the stack is also very cheap.
Second variant:
int* a = new int[N];
does not require MSVC+language-extensions nor a C++14 compiler, this allocates memory from the heap equivalent to sizeof(int) * N
.
It does not get automatic lifetime - you will need to delete[]
the memory when you are done with it. Allocating on the heap can be expensive, especially in multithreaded applications.
There may be cases where the memory needs of a program can only be determined during runtime. Then you should use :
int *A = new int[N]; //it's dynamic memory. Mean it can be change at runtime.
Otherwise You should use :
int A[N];
Which is faster:
int A[N];
is faster because it can be stored on the runtime stack, and when entering the function it will just change the stack pointer by a larger number to allocate room.
int *A = new int[N];
is slower because you have to take the time to find a large-enough consecutive block of memory. Also, it is less likely to be on an easily-accessible part of the computer's storage.
For more information, see this related stack overflow question.
Which is better:
Regarding which one is "better" overall, it depends on the specific case. See this stack overflow question for more details.
compile-time array: C++ 11 has a new container named std::array, like boost::array, which is similar to standard container and can replace the traditional C array.
runtime array: vector is a good choice, you can reserve its size when created. other sequence containers can also be an array.
When N is very large you should use dynamic memory allocation otherwise it will give stack over flow exception.