【问题标题】:Count number of invocations of HashMap/HashTable统计HashMap/HashTable的调用次数
【发布时间】:2012-08-29 07:05:42
【问题描述】:

我有一个 java 程序,其中有很多 HashMap/HashTable 用于映射键值对。现在我想分析或者更确切地说计算在我的程序中调用了多少次 get() 和 put() 方法。

我采用的方法是扩展 Java HashMap/HashTable 类并引入一个名为 count 的成员,并在 get() 和 put() 方法中每次调用该方法时递增计数。这将涉及大量重构,因为我必须去删除 HashMap/HashTables 的所有实例化来实例化我的扩展类。这种方法是否合理,还是有其他更好的方法来保持这个计数?

【问题讨论】:

  • 我认为你可以通过反射和在方法上插入钩子来做到这一点。最初的谷歌搜索表明这是可能的,至少。
  • 上帝保佑搜索和替换所有! :P
  • @bdares 您能否详细说明反射方面(我理解反射)如何完成。

标签: java hashmap hashtable


【解决方案1】:

此类任务的最佳解决方案是使用 Profiler,例如 YourKitJProfiler。探查器对被探查的 JVM 加载的所有(或部分)类执行 "instrumentation" 以准确执行您需要的操作:计数和测量所有方法调用,无需修改一行代码。

上述两个分析器都附带试用许可证。一旦你尝试过它们,你可能会买一个,因为它们在很多情况下都非常有用。

【讨论】:

  • +1 这是最好的方法。如果这不是一个选项,您可以修改 HashMap 或 Hashtable 以进行测试。
  • @PeterLawrey 我同意这是最好的方法,但现在不是一个选择。我想我会继续修改 HashMap|HashTable 并继续我的做法。
  • 要修改原始文件,您需要将它们预先添加到引导类路径或将它们添加到 lib/endorsed 目录中的 jar 中
【解决方案2】:

您可以使用分析工具来告诉您一个方法运行了多少次以及执行代码需要多长时间。例如,您可以在 Eclipse IDE 中执行此操作:http://www.eclipse.org/projects/project.php?id=tptp.performance

【讨论】:

    【解决方案3】:

    您可以使用继承:https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

    public class Main{
        public static void main(String[] args){
              HashMap<Integer,Integer> mymap = new myMap<Integer,Integer>();
              mymap.put(3,4);
              mymap.put(5,6);
              System.out.println(mymap.get(3));//this will print 4;
              System.out.println(mymap.getCountGets());//this will print 1 
              System.out.println(mymap.getCountPuts());//this will print 2
        }
    }
    class myMap<K,V> extends HashMap<K,V> {
    
    public myMap(){
        countPuts = 0;
        countGets = 0;
    }
    private int countPuts, countGets ;
    
    @Override
    public V put(K k, V v){
        countPuts++;
        return super.put(k, v);
    }
    @Override
    public V get(Object k){
        countGets++;
        return super.get(k);
    }
    
    public int getCountGets(){
        return countGets;
    }
    
    public int getCountPuts(){
        return countPuts;
    }
    

    }

    【讨论】:

    • 你需要解释你的答案。
    • 继承是一个OOP概念,利用超类的行为,不仅如此,还修改它(覆盖)。
    猜你喜欢
    • 2015-09-28
    • 2022-10-15
    • 2023-03-26
    • 2010-11-15
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 2020-10-11
    • 2016-11-12
    相关资源
    最近更新 更多