【问题标题】:What's more efficient for counting, Arrays or Hashmap(or Set) [closed]计数,数组或哈希图(或集合)更有效[关闭]
【发布时间】: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


【解决方案1】:

根据性能比较这两种方法,两种算法都以 O(n) 时间复杂度运行,其中 n 是所提供字符串的大小。此外,两种情况下的空间复杂度都是 O(1)。 谈到偏好,这取决于开发人员和开发产品的团队。尽管 HashMap 方法似乎更精巧、更干净(又是开发人员的意见)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 2016-08-08
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多