简体   繁体   中英

Best way to define a constant identifier?

In my java application one of my objects has exactly one value from a set of values. Now I wonder how to define them to increase the performance:

private static final String ITEM_TYPE1= "type1"

private static final int ITEM_TYPE1= 1

Does defining int better than string? (I should convert the value to string so I like to define as string but just fearing for performance reasons because comparing ints is simpler than srtings maybe)

EDIT : I am aware of enums but I just want to know whether ints has more performance than strings or not? This depends on how JDK and JRE handle the undergoing. (In Android dalvik or ART ..)

In my java application one of my objects has exactly one value from a set of values

That is what java enums are for.

Regarding the question "have ints more performance than strings", that is almost nonsensical.

You are talking about static constants. Even if they are used a 100 or a 1000 times in your app, performance doesn't matter here. What matters is to write code that is easy to read and maintain. Because then the JIT can kick in and turn it into nicely optimized machine code.

Please understand: premature optimisation is the root of all evil! Good or bad performance of your app depends on many other factors, definitely not on representing constants as ints or strings.

Beyond that: the type of some thing in Java should reflect its nature . If it is a string, make it a string (like when you want to mainly use it as string, and concatenate it to other strings). When you have numbers and deal with them as numbers, make it an int.

First of all, an int has always a fixed size which it uses in memory, on most systems it's 4 bytes (I guess on Java always).

A String is a complex type which means that it takes not only the bytes of the actual string data but also additional like the length of the string and so on.

So if you have the choice between String and int , you should always chose int . it does not take so much place and is faster to operate with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM