你能用char[65536][]
吗?其中顶部或底部 16 位是其他 16 位数组的索引。这可以使用少于 4 * X 每个条目。
抬头
private final char[][] bitsArray = new char[65536][];
public int countFor(int num) {
int topBits = num >>> 16;
int lowerBits = num & 0xFFFF;
char[] lowerBitsArray = bitsArray[topBits];
int count = 0;
for(char l : lowerBitsArray)
if(l == lowerBits)
count++;
return count;
}
如果计数永远不会超过 1,那么 BitSet 可能是更好的选择。(可能是一组 BitSet,具体取决于数据模式)例如,如果您要记录看到的 IP 地址,您可能不需要担心 0. 、 10.、 127.* 或 224-255.*
an int[]
orchar[]
访问速度是否更快,包括转换为 int。
public static void main(String... args) {
char[] chars = new char[1000000];
for (int i = 0; i < 5; i++)
timeSum(chars);
int[] ints = new int[1000000];
for (int i = 0; i < 5; i++)
timeSum(ints);
}
private static int timeSum(char[] chars) {
long start = System.nanoTime();
int sum = 0;
for (char ch : chars) {
sum += ch;
}
long time = System.nanoTime() - start;
System.out.printf("Took %,d us to sum %,d chars%n", time / 1000, chars.length);
return sum;
}
private static int timeSum(int[] ints) {
long start = System.nanoTime();
int sum = 0;
for (int i : ints) {
sum += i;
}
long time = System.nanoTime() - start;
System.out.printf("Took %,d us to sum %,d ints%n", time / 1000, ints.length);
return sum;
}
印刷
Took 5,378 us to sum 1,000,000 chars
Took 11,551 us to sum 1,000,000 chars
Took 437 us to sum 1,000,000 chars
Took 407 us to sum 1,000,000 chars
Took 407 us to sum 1,000,000 chars
Took 5,539 us to sum 1,000,000 ints
Took 532 us to sum 1,000,000 ints
Took 530 us to sum 1,000,000 ints
Took 511 us to sum 1,000,000 ints
Took 507 us to sum 1,000,000 ints
我的结论是缓存效率比转换成本更重要。