1

Recently, I had to implement a business rule in a certain project. The rule basically consisted of checking a range between 1 and 12, values that would be used later, in some way, with Bootstrap.

First, since it is a numeric data type, I declared it as int. However, as the range wasn't that big, I started to question whether I should really use the int or byte type.

We know the difference between int and byte. I thought using byte would be enough for such a business rule, as int would consume more memory space.

Now, I've been looking at a few other projects — some prominent ones on the market, and it looks like they use the int type in, let's say, a variable that defines the size of a hash's salt.

I believe that in my case, and some others like this one from salt, using numeric data type byte would be better instead of int. However, maybe I'm not sure about this, so I'd like to hear the opinion of someone who has more knowledge and could argue better, so that I can remedy the doubt.

2
  • 3
    Does this answer your question? Is premature optimization really the root of all evil? - on in other words, it doesn't matter, stop wasting your time thinking about it and deal with an actual problem instead. May 8, 2022 at 21:31
  • 1
    Generally, there's no point to make a single variable a byte instead of an int - it only matters when you have a big array of bytes instead of ints.
    – user253751
    May 9, 2022 at 10:22

1 Answer 1

3

The rule basically consisted of checking a range between 1 and 12

Bytes don't have a range between 1 and 12. Therefore, by using a byte, you don't make your code or your intentions clearer in any way.

Actually, you make them less clear. Bytes have a slightly different usage than numbers. They represent a chunk of memory.

Here, you want to use it to represent what is actually a number—an integer, actually. But instead of telling “that's an integer,” you want your code to tell “that's a chunk of memory,” which makes your code very difficult to understand.

And that's the problem. You're making your code bad on purpose, for the sake of saving memory. Sometimes, it makes sense: embedded programming, when the memory counts in kilobytes, is one example (for instance ATmega328 has 2 KB SRAM, so, indeed, every byte counts).

Is this your case? If no, you're doing what's called premature optimization. And often, people who do premature optimization end up writing code which is less optimized as a result. For instance, by using a byte in your case, you may end up forcing the virtual machine to perform conversion between bytes and integers, which may not only cancel what you're trying to save in terms of memory, but make your code slower.

Not the answer you're looking for? Browse other questions tagged or ask your own question.