简体   繁体   English

Java中的2D数组

[英]2D array in Java

Which of the following is faster in Java? Java中哪一个更快? Is there any other way that is faster than any of these? 有没有比其中任何一种更快的其他方式?

int[][] matrix = new int[50][50];

for (int k=0;k<10;k++){
// some calculations here before resetting the array to zero
      for (int i = 0; i <50; i++) {
            for (int j = 0; j <50; j++) {
                matrix[i][j]=0;
            }              
        }
}

Or this: 或这个:

int[][] matrix = new int[50][50];

    for (int k=0;k<10;k++){
// some calculations here before resetting the array to zero 
          matrix = new int[50][50];
    }

The fastest way to perform an action that leaves the variable, "matrix" in an equivalent state at the end of a run is int[][] matrix = new int[50][50]; 在运行结束时执行将变量“矩阵”保持在等效状态的动作的最快方法是int[][] matrix = new int[50][50];

However, none of these solutions are equivalent in terms of number of operations or memory thrash. 但是,这些解决方案在操作次数或内存抖动方面都不相同。 The statement I've provided is what you are looking for. 我提供的声明就是你要找的。

Update: With your updated question where you are manipulating matrix and then resetting it. 更新:使用您更新的问题,您在哪里操作矩阵然后重置它。

Your second example will likely be faster on each iteration. 您的第二个示例在每次迭代时可能会更快。 The thought being that it is faster to allocate memory than iterate and set a variable 50^2 times. 这个想法是,分配内存比迭代更快,并设置变量50 ^ 2倍。 Though this is a question for a profiler. 虽然这是一个剖析器的问题。 In general, zeroing out memory is something that is better optimized by the JVM than your application. 通常,将内存归零是JVM比应用程序更好地优化的。

This being said, it is important to remember than memory allocation is not without caveats in extreme scenarios. 这就是说,重要的是要记住,在极端情况下,内存分配并非没有警告。 If you allocate and trash memory too often, you may have a suboptimal GC experience. 如果过于频繁地分配和删除内存,则可能会出现次优的GC体验。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM