【发布时间】:2020-09-20 00:22:49
【问题描述】:
假设我们被要求计算并打印给定字符串中每个字符的出现次数。为简单起见,字符串只有小写字母。我写了这两个函数,我想知道哪一个在 Java 中更高效/更可取。
功能一:
private void countAndPrintArray1(String str){
int[] a = new int[26];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int index = c - 'a';
a[index] = a[index] + 1;
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = a[c -'a'];
System.out.println(c+" -> "+ freq);
}
}
功能2:
private void countAndPrintArray2(String str){
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = map.getOrDefault(c, 0) + 1;
map.put(c, freq);
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = map.get(c);
System.out.println(c+" -> "+ freq);
}
}
【问题讨论】:
-
测试它们时你看到了什么?
-
两者都是可接受的解决方案。
-
我的预感是 Function1 会更好,因为数组具有良好的参考局部性,但从不凭直觉,我们应该始终先进行基准测试。使用 JMH 进行基准测试
-
你有更好的机会在 Code Review 上提出这个问题。
标签: java arrays performance hashmap