HashMap vs Switch 语句性能

HashMap vs Switch statement performance(HashMap vs Switch 语句性能)

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

问题描述

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

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.

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

Understandably, if a switch statement is written as such,

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

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

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;
}

什么会提供更高的吞吐量,lookupswitch 或 HashMap?HashMap 的开销是否在早期为查找开关提供了优势,但最终随着案例/条目数量的增加而逐渐减弱?

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?

我使用 JMH 尝试了一些基准测试,这是我使用的结果和代码.https://gist.github.com/mooman219/bebbdc047889c7cfe612正如你们提到的,lookupswitch 语句优于 HashTable.我仍然想知道为什么.

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.

推荐答案

视情况而定:

  1. 如果有几个项目 |固定物品.如果可以,请使用 switch(最坏情况 O(n))

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

如果有很多项目或者你想在不修改太多代码的情况下添加未来项目--->使用hash-map(访问时间被认为是常数时间)

If there are 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)

适合你的情况.您不应该担心性能,因为执行时间的差异是纳秒.只关注代码的可读性/可维护性.是否值得优化一个简单的案例以提高几纳秒?

For your case. You should not worry about performance because the difference in execution time is nanoseconds. Just focus on readability/maintainability of your code. Is it worth optimizing a simple case to improve a few nanoseconds?

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

本文标题为:HashMap vs Switch 语句性能

基础教程推荐