Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

java - Comparing Performance of int and Integer

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

I am writing an application in Java. In most of the places of primitive data types, I use int; and for objects, I use Integer. So I am confused- which one is the best in places, where we have to use objects.

According to performance, which one is best for a Java application?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...