Why doesn't Android use more enums?

前端 未结 3 1570
抹茶落季
抹茶落季 2020-12-02 09:27

I\'ve started to really like using C# and Java enums in my code for several reasons:

  • They are much more type-safe than integers, strings, or sets of boolean fl
相关标签:
3条回答
  • 2020-12-02 10:02

    A colleague of mine performed a small test regarding this situation. He auto generated a class and an enum with the same amount of "enums". I believe he generated 30000 entries.

    The results were:

    • .class for the class was roughly 1200KB
    • .class for the enum was roughly 800KB

    Hope this helps someone.

    0 讨论(0)
  • 2020-12-02 10:06

    Integers are smaller, and require less overhead, something that still matters on mobile devices.

    0 讨论(0)
  • 2020-12-02 10:22

    This answer is out of date as of March 2011.

    Enums can be used on Froyo and up - according to this answer (Why was “Avoid Enums Where You Only Need Ints” removed from Android's performance tips?) from a member of the Android VM team (and his blog).


    Previous Answer:

    The official Android team recommendation is to avoid enums whenever you can avoid it:

    Enums are very convenient, but unfortunately can be painful when size and speed matter. For example, this:

    public enum Shrubbery { GROUND, CRAWLING, HANGING }
    

    adds 740 bytes to your .dex file compared to the equivalent class with three public static final ints. On first use, the class initializer invokes the method on objects representing each of the enumerated values. Each object gets its own static field, and the full set is stored in an array (a static field called "$VALUES"). That's a lot of code and data, just for three integers. Additionally, this:

    Shrubbery shrub = Shrubbery.GROUND;
    

    causes a static field lookup. If "GROUND" were a static final int, the compiler would treat it as a known constant and inline it.

    Source: Avoid Enums Where You Only Need Ints

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