Comparing Performance of int and Integer

后端 未结 5 2079
天涯浪人
天涯浪人 2020-12-18 18:26

Which one is best in programming - int or Integer? Especially whenever both are doing the same task?

I am writing an appli

相关标签:
5条回答
  • 2020-12-18 19:01

    As an alternative view.... perhaps you should use neither Integer nor int.

    If the value is really an object with behaviour - like say an amount of money, or a distance or something, then perhaps you should be using an object with behaviour.

    You can see more about this kind of thing here:

    http://www.time4tea.net/wiki/display/MAIN/Microtypes

    Although this may be "slower", the additional type safety will make the programming, testing and debugging of your system much easier & faster.

    0 讨论(0)
  • 2020-12-18 19:04

    Use int wherever possible. Use Integer only if:

    • You need a way to represent "no value" or "uninitialized". Integer can be null, an int always has an int value.
    • You want to use collections like List (though you can use int externally and have autoboxing hide the fact that the collection internally stores Integer instances).
    • You're using an API, framework or tool that requires you to use Integer or Object, or doesn't work with primitive types.
    • You need to be able to synchronize on the object (very unlikely).
    0 讨论(0)
  • 2020-12-18 19:05

    int is primitive, Integer is an int wrapped up as an object.

    It really depends how you are going to be using them.

    0 讨论(0)
  • 2020-12-18 19:12

    int a primitive, typically it should be faster. It just carries the raw number data.

    Integer is an object, it carries some extra stuff so you e.g. can put the number in lists.

    0 讨论(0)
  • 2020-12-18 19:18

    Use int when possible, and use Integer when needed. Since int is a primitive, it will be faster. Modern JVMs know how to optimize Integers using auto-boxing, but if you're writing performance critical code, int is the way to go.

    Take a look at this and this article. Although you shouldn't treat them as absolute truths, they do show that objects will be slower than their primitive counterparts.

    So, use int whenever possible (I will repeat myself: if you're writing performance critical code). If a method requires an Integer, use that instead.

    If you don't care about performance and want to do everything in an object oriented fashion, use Integer.

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