Hello, just thought - is it still relevant to use types like Byte
in a project when the variable is used just couple of times and usually converted to Int
(e.g. MutableList
accepts only Int
parameter)?
Not much, I think that on modern architectures those take the same space Int
if not Long
s take in memory. And have the same performance when you do any computation
So, it’s a fake optimization and in worse case it’s even opposite because of conversions? Any modern articles on this topic?
You might be looking at this from the wrong angle.
Always profile before doing any optimization.
Write code that is easy to read and well structured, then profile and adjust what is slow.
Whether changing data types makes a difference depends on what does the rest of your code do.
Not an expert but
unless you are dealing with some low level data, like data from an image file, then you will use bytes, otherwise, stick to Int or Long
If you work with numbers and you just know they are small, then stick to Int. Byte/Short makes sense in cases like:
- Processing binary data.
- Big arrays, millions of items - consider ByteArray/ShortArray.
Small ints are a necessity when you have big arrays used mainly for small counts and enough memory is not available… Otherwise, they add overhead…
I don’t have a link available at the moment, but this was asked to Roman Elizarov and he replied that Byte
etc are here mostly for serialization / storage. When writing an object to a file, it may have storage benefits to use a smaller type. At runtime though, it makes little difference (the JVM doesn’t even have mathematical operators for anything smaller than Int
, so in calculations it just doesn’t make a difference).
Looks like another complain for C++ developers.
If you are in a situation where the difference in speed is measurable, what’s popular does not concern you. Even in C++ it’s rare to be able to see the difference, and one some architectures it’s the same anyway.