0
A) int a[][]=new int[20][32];
   a[2][3]=1;
   if(a[2][3]==1)
   {
    System.out.println("true");
   }
B) int a[]=new int[20];
   a[2]=12;
   if ((a[2] & (1 << 3)) != 0)
   {
    System.out.println("true");
   }

在 A)我使用 2D int array ,我正在检查 [2,3] 是否为 1
在 B)我使用 Int 的索引作为第二个暗淡。mat.Here 我正在检查数组的第二个元素的 3 位。哪一个更好?为什么在速度和记忆的背景下?

4

2 回答 2

1

我要打破自己的规则,给出一个基于意见的“答案”。

显然,您的第一种方法更具可读性,但会占用更多内存。如果您在一个非常大的数组上执行此操作,并且内存受限,那么按位掩码是有意义的。

我强烈建议您避开像这样的“聪明”技术,除非它们被很好地封装在更高级别的函数中——此时,对于这样一个简单的例子,您将失去性能优势(如果有的话)但是选择提高内存效率。

当然,当第二维不是 32 时,效率增益会更少(并且可能需要进一步解决特定位的工作量猛增)。

于 2013-10-02T17:22:47.010 回答
1

Testing bits may time more time than testing plain ints for small dimensions. For bigger dimensions however, it will become worth it - the second example uses about 32 times less memory (ignoring the overhead of having an array-object), and that means that more of it will stay in caches, which are much faster than main memory (which is very slow compared to a CPU). On today's machines, it is often the case that using more instructions so that you can use the cache better makes things much faster, however, when the entire thing is tiny to begin with, the overhead of testing bits would probably not be worth it.

There is an other case in which using "tiny bit-arrays" like the second example can work out really well: when you can exploit the fact that they're ints instead of just accessing the bits individually. For example, if you intend to do boolean arithmetic on whole 32bit chunks at the time, or if you want to count the number of 1's, or if you want to get the lowest index that has a 1 (especially if you really wanted a mask instead of the index).

于 2013-10-02T17:35:31.537 回答