HashMap vs Switch语句性能 [英] HashMap vs Switch statement performance

查看:797
本文介绍了HashMap vs Switch语句性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HashMap本质上具有O(1)性能,而开关状态可以具有O(1)或O(log(n)),具体取决于编译器是使用tableswitch还是lookup switch。

可以理解的是,如果switch语句是这样写的,那么

  switch(int){
案例1:
案例2:
案例3:
案例4:
默认:
}
pre>

那么它将使用一个tableswitch,并且显然比标准HashMap具有性能优势。但是如果switch语句很稀疏呢?这些是我将要比较的两个例子:

  HashMap< Integer,String> example = new HashMap< Integer,String>(){{
put(1,a);
放(10,b);
put(100,c);
放(1000,d);
}};

  switch(int){
情况1:
返回a;
案例10:
返回b;
情况100:
返回c;
案例1000:
返回d;
默认值:
返回null;
}

什么会提供更高的吞吐量,lookupswitch或HashMap?
HashMap的开销是否为查找开关提供了一个优势,但随着案例/条目数量的增加,最终会逐渐减少?
$ b 编辑:我尝试了一些使用JMH的基准测试,这里是我使用的结果和代码。 https://gist.github.com/mooman219/bebbdc047889c7cfe612
正如你们提到的那样,lookupswitch的声明胜过HashTable。我仍然想知道为什么。

解决方案

它取决于:


  1. 如果有几项| |固定项目。使用开关(最坏情况O(n))如果有很多项目或者你想添加未来项目而不修改很多代码--->使用开关哈希映射(访问时间被视为常量时间)


  2. 您的情况。您不应该担心性能,因为两种情况下的时间消耗都非常低。只关注代码的可读性/可维护性。



A HashMap essentially has O(1) performance while a switch state can have either O(1) or O(log(n)) depending on if the compiler uses a tableswitch or lookup switch.

Understandably, if a switch statement is written as such,

switch (int) {
    case 1:
    case 2:
    case 3:
    case 4:
    default:
}

then it would use a tableswitch and clearly have a performance advantage over a standard HashMap. But what if the switch statement is sparse? These would be two examples that I would be comparing:

HashMap<Integer, String> example = new HashMap<Integer, String>() {{
        put(1, "a");
        put(10, "b");
        put(100, "c");
        put(1000, "d");
}};

.

switch (int) {
    case 1:
        return "a";
    case 10:
        return "b";
    case 100:
        return "c";
    case 1000:
        return "d";
    default:
        return null;
}

What would provide more throughput, a lookupswitch or HashMap? Does the overhead of the HashMap give the lookupswitch an advantage early but eventually tapers off as the number of cases/entries increase?

Edit: I tried some benchmarks using JMH, here are my results and code used. https://gist.github.com/mooman219/bebbdc047889c7cfe612 As you guys mentioned, the lookupswitch statement outperformed the HashTable. I'm still wondering why though.

解决方案

It depends on:

  1. If there are a few items | fixed items. Using switch ( worst case O(n))

  2. If there a a lot of items OR you want to add future items without modifying much code ---> Using hash-map ( access time is considered as constant time)

  3. For your case. You should not worry about performance because the time consume for both-case is very low. Just focus on readability/maintainability of your code.

这篇关于HashMap vs Switch语句性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆