什么是数组初始化的时间复杂度? [英] What is the time complexity of array initialization?

查看:763
本文介绍了什么是数组初始化的时间复杂度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下用C或C ++2案件数组初始化:

Consider following two cases of Array initialization in C or C++ :

案例1:

int array[10000] = {0}; // All values = 0

案例2:

int array[10000];
for (int i = 0; i < 10000; i++) {
    array[i] = 0;
}

难道他们都采取同一时间?什么是案例1的复杂性?并且,哪一个更好呢?

Do they both take same time ? what is the complexity of Case 1? and, Which one is better?

推荐答案

在数组是一个静态的持续时间(全局变量)的情况下,我会说第一个是多preferrable,因为它不 ŧ要求任何code - 它由运行时环境初始化。

In the case of the array being of static duration (global variable), I'd say the first one is much preferrable, since it doesn't require any code - it is initialized by the runtime-environment.

如果该变量是一个自动的持续时间(局部变量),其中之一是更好,如果任一比其它更好的,依赖于编译器。最可能的是,两者都将是非常相似的。

If the variable is a of automatic duration (local variable), which one is better, if either is better than the other, depends on the compiler. Most likely, both will be very similar.

为自动存储时间变量comlexity是所有情况下为O(n)。第一种情况是静态存储时间变量O(1)。

The comlexity for the automatic storage duration variable is O(n) for all cases. The first case is O(1) for a static storage duration variable.

当然,如果你想以填补数组值5,第二个选项是要好得多,因为它不需要在源文件中写10000 5

Of course, if you wanted to fill array with the value 5, the second option is much better because it doesn't require writing 10000 5 in the source file.

您还可以发现,使用 memset的(数组,0,sizeof的(阵列)); 比都好 - 再次,根据不同的编译器。这仍然是O(n),但需要填写阵列的实际时间可能会缩短,因为 memset的可以更好地比编译器生成的循环情况进行了优化[和它做什么的初始化的变量。 memset的将不填充数组与 5 工作的。

You may also find that using memset(array, 0, sizeof(array)); is better than both - again, depending on the compiler. This is still O(n), but the actual time it takes to fill the array may be shorter, because memset may be better optimized than what the compiler generates for your loop case [and what it does for initialized variables]. memset won't work for filling the array with 5 either.

您也可以使用的std ::填充(阵列和放大器;数组[10000],5); 设定值5在所有的数组,编译器必应是优化了体面的工作。

You could also use std::fill(array, &array[10000], 5); to set the value 5 in all the array, and the compiler will should a decent job of optimizing that.

最后,我要指出的是,这些类的东西才真正重要,如果他们在被执行了很多code做的事情。这是因为填充40KB的数据花了足够长的时间来真正担心自身的很长一段时间。就像20年以上。

Finally, I should point out that these sort of things only REALLY matter if they are doing in code that gets executed a lot. It's a long time since filling 40KB of data took long enough to really worry about on its own. Like 20+ years.

这篇关于什么是数组初始化的时间复杂度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆