Java Enums - Switch statements vs Visitor Pattern on Enums - Performance benefits?

前端 未结 1 802
清酒与你
清酒与你 2021-01-05 03:36

I have been searching around for days to find an answer to this performance based issue.
After digging the Internet so far I have learned that there are couple of ways

相关标签:
1条回答
  • 2021-01-05 04:27

    Enums are, generally speaking, comparable in performance to int constants, if used in a switch statement (1).

    Maybe you should rather consider something along the lines of constant specific method implementations? e.g.

    public enum Mode {
    
      ON { Color color() {return Color.GREEN;}},
      OFF { Color color() {return Color.RED;}},
      STANDBY { Color color() {return Color.YELLOW;}},
      DEFAULT { Color color() {return Color.BLACK;}};
    
      abstract Color color();
    
    }//enum Mode
    

    And then use

    getMode().color();
    

    instead of a switch statement?!

    However, I think that for a "get a color only case", there is maybe no need for methods at all.

    In general, I highly recommend you Effective Java for your bookshelf. Chapter 6 would be the one that discusses Enums and Annotations.

    0 讨论(0)
提交回复
热议问题