[英]C/C++ Allocation
Giving a number X and reading X numbers into an uni-dimensional array, which of the following ways is the best(fastest as execution time)?给出一个数字X并将X个数字读入一维数组,以下哪种方式最好(执行时间最快)?
Please note that X is a number between 1 and 1000000请注意 X 是 1 到 1000000 之间的数字
scanf("%d", &x);
int array[x];
//continue reading X numbers into array
Or或者
scanf("%d", &x);
int array[1000000];
//continue reading X ...
Or或者
scanf("%d", &x);
int * array = malloc(x*sizeof(int));
//same as above
free(array);
Or the C++ dynamic allocation method?还是C++动态分配方法?
Note 1: that I am posting this from a mobile phone, I hope the format for the code above is fine, if not, I ask nicely somebody (<3) to edit it, since it is painfull to indent code from a phone.注意 1:我是从手机上发布的,我希望上面代码的格式没问题,如果没有,我会请人(<3)编辑它,因为从手机中缩进代码很痛苦。
Note 2: How could I test what I asked above?注 2:我如何测试我上面提出的问题?
You'll get compilation error for this code:您将收到此代码的编译错误:
scanf("%d", &x);
int array[x];
x should be known at compilation time in this case.在这种情况下,应该在编译时知道 x。
When using int array[1000000]
you allocate memory on the stack, not in the heap, so it's fundamental difference comparing to malloc
or new operator
.使用int array[1000000]
您在堆栈上分配内存,而不是在堆中,因此与malloc
或new operator
相比,这是根本区别。 It would be faster because it takes actually only one CPU command of modifying stack pointer.它会更快,因为它实际上只需要一个 CPU 命令来修改堆栈指针。
If comparing malloc
and new
, malloc
will be faster because new will eventually call malloc
inside.如果比较malloc
和new
, malloc
会更快,因为 new 最终会在内部调用malloc
。 But the performance gain will be tiny, It doesn't worth to optimize your c++ program in this way, just use c++ when you need to allocate dynamic memory.但是性能提升会很小,用这种方式优化你的c++程序是不值得的,只需要在需要分配动态内存时使用c++。
Since there appears scanf
(and the comments assume that there's another million calls to scanf
) any questions regarding the memory allocation in combination with "Which is fastest?"由于出现scanf
(并且评论假设还有一百万次调用scanf
)关于内存分配以及“哪个最快?”的任何问题。 can be universally answered with: "Yes" (read as: irrelevant).可以普遍回答:“是”(读作:无关紧要)。
While automatic storage ("stack allocation") is generally faster than freestore, it is entirely insignificant compared to the time you will spend in scanf
.虽然自动存储(“堆栈分配”)通常比 freestore 快,但与您将在scanf
花费的时间相比,它完全微不足道。 That being said, it is usually (not necessarily, but usually) dynamic deallocation which is slow, not allocation.话虽如此,它通常(不一定,但通常)是缓慢的动态释放,而不是分配。
A couple of points to note in general on that code:关于该代码,一般需要注意几点:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.