HashMap vs Switch statement performance

后端 未结 4 1710
梦谈多话
梦谈多话 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 13:57

    If I have that kind of example I use Guava ImmutableMaps (sure You can use java 9 builder as well).

    private static final Map EXAMPLE = ImmutableMaps.>builder()
        .put("a", "100")
        .put("b", "200")
        .build(); 
    

    That way they are immutable and initated only once.

    Sometimes I use strategy pattern that way:

    private static final Map EXAMPLE = ImmutableMaps.>builder()
        .put("a", new SomethingCool())
        .put("b", new BCool())
        .build(); 
    
    private static final Command DEFAULT= new DefCommand();
    

    Use:

    EXAMPLE.getOrDefault("a", DEFAULT).execute(); //java 8
    

    About performance just pick readability. You will thank me later (1 year later) :D.

提交回复
热议问题