Java Enum.valueOf() efficiency when value does not exist

后端 未结 7 3458
深忆病人
深忆病人 2021-02-20 17:58

Which would you consider more efficient?

The use of \'WeekDay\' is just an example:

public enum WeekDay {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDA         


        
相关标签:
7条回答
  • 2021-02-20 18:54

    I know its an old post, but I believe following result will be still interesting. I run 10000000 tests to find an element in enum ENUM {FIRST, SECOND, THIRD, FOURTH, LAST} using JDK 1.8. The table below shows time required by simple loop and valueOf().

    text     loop   valueOf  ratio
    ------------------------------
    "FIRST"  121    65       186%
    "LAST"   188    57       330%
    "foo"    155    8958     1.7%
    

    Conclusion - I wouldn't use valueOf() if I expect values not matching enum.

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