开发者

how important is it to declare the correct variable type

开发者 https://www.devze.com 2023-04-08 13:16 出处:网络
If I have a number only between 1 &开发者_JAVA技巧 10 is it overkill declare it as int or should you use short, Long, sbyte?

If I have a number only between 1 &开发者_JAVA技巧 10 is it overkill declare it as int or should you use short, Long, sbyte?

int x = 5; or sbyte x = 5;


int is handled faster on 32 bit processors, since its size is equal to CPU register size. If you don't have additional requirements (the need to conserve memory, for example), use int.


Without more context I would say just use an int. Overkill only matters when you have space constraints or it overly complicates what you're trying to do.


Not really unless your are tying to get minuscule amounts of performance and memory footprint out of your application.

However I would suggest using the correct type if not for readability purposes and also so that if the value increases above it's allocated type size then this potential bug will be caught at compile time.


Simplicity in your code is an important feature for long term maintainability. Unless optimization is vitally important such as in super high speed applications (games where instant reactions are critical), don't waste time worrying over a few bytes that would make it harder for the next guy to understand.


When in doubt, don't optimize. Over optimization in the early stages of a code base is usually a bad idea and leads to abstraction leakage, bad versatility of the code base and hard to debug problems. Stick with the most common types in the type system and whenever you discover that the type only needs to be short or uint, you can always change type later on.

It's easier to start out wide and narrow the types down than the other way around and before you have a working code base that integrates with 3rd party systems and such, it's impossible to know exactly where the boundaries in your code needs to be drawn.


Call a dog a dog and a salesman a salesman. Declaring your variables in the right type is fundamental for code readability and accuracy.

Now, for your example, if you are sure it's only from one to 10, you can use sByte. I would, however, use int. We should not overcomplicate, whenever we can.

Also, as well noticed by @ElRonnoco, if you are planning to execute calculations, you might get an overflow error when dealing with small numeric types so you should stick to int for most things.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号