哪种方式更适合阵列访问?

Sat*_*evi 3 c c++ arrays algorithm

我有一个函数,我使用一个常量数组:

void function(int Id){
int array1[4] = {4 constants};
int array2[4] = {4 constants};
   for(int i=0; i<4; i++){
   //accessing the array 1&2 for computation;
   }
}
Run Code Online (Sandbox Code Playgroud)

将有近百万次void function(int Id)访问main().

我的问题是,在头文件中声明array1和array2并在内部访问function()是否更好,或者现在是否可以动态声明它们?

哪种方式会更快(考虑从头文件访问或动态声明)?

编辑:只能访问数组并且不会在里面修改数组function().

Sim*_*ott 15

如果数组不会改变,并且不会在另一个函数中重用,那么最好将它们设置为静态.这避免了在每次调用函数时都需要在堆栈上构造数组.

void function(int Id){
    static const int array1[4] = {4 constants};
    static const int array2[4] = {4 constants};
    for(int i=0; i<4; i++){
        //accessing the array 1&2 for computation;
   }
}
Run Code Online (Sandbox Code Playgroud)

编辑添加最好避免在数组声明和循环表达式中使用"幻数"4.如果没有这样做,很容易改变数组大小而忘记更改循环表达式.这可以通过使数组大小为常量,或者在循环表达式中使用sizeof()来完成,如此堆栈溢出问题所示:如何在C中确定数组的大小?

  • 这种方法的另一个优点是数组只在函数中可见; 他们没有不必要地接触到其他程序. (3认同)

Rax*_*van 5

我认为最好的方法是:

void function(int Id){
    static const int array1[4] = {4 constants};
    static const int array2[4] = {4 constants};
   for(int i=0; i<4; i++){
   //accessing the array 1&2 for computation;
   }
}
Run Code Online (Sandbox Code Playgroud)

但最好只做一个小测试,看看哪一个是最快的.Raxvan.

  • 尝试在解决方案中添加一些解释.人们常常在这里学习而不是简单地解决他们的问题.(可能两者兼而有之) (3认同)