HashMap vs Switch statement performance

后端 未结 4 1743
梦谈多话
梦谈多话 2021-01-30 13:14

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.

Under

4条回答
  •  没有蜡笔的小新
    2021-01-30 14:00

    It depends:

    1. If there are a few items | fixed items. Using switch if you can ( 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 different execution time is very small. Just focus on readability/maintainability of your code. Is it worth to optimize a simple case to improve a few nanoseconds?

提交回复
热议问题