Long vs Integer, long vs int, what to use and when?

前端 未结 7 721
醉梦人生
醉梦人生 2020-12-12 12:14

Sometimes I see API\'s using long or Long or int or Integer, and I can\'t figure how the decision is made for that?

相关标签:
7条回答
  • 2020-12-12 13:07

    Integer is a signed 32 bit integer type

    • Denoted as Int
    • Size = 32 bits (4byte)
    • Can hold integers of range -2,147,483,648 to 2,147,483,647
    • default value is 0


    Long is a signed 64 bit integer type

    • Denoted as Long
    • Size = 64 bits (8byte)
    • Can hold integers of range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
    • default value is 0L


    If your usage of a variable falls in the 32 bit range, use Int, else use long. Usually long is used for scientific computations and stuff like that need much accuracy. (eg. value of pi).

    An example of choosing one over the other is YouTube's case. They first defined video view counter as an int which was overflowed when more than 2,147,483,647 views where received to a popular video. Since an Int counter cannot store any value more than than its range, YouTube changed the counter to a 64 bit variable and now can count up to 9,223,372,036,854,775,807 views. Understand your data and choose the type which fits as 64 bit variable will take double the memory than a 32 bit variable.

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