O
O
olexandr72014-10-02 13:19:49
Java
olexandr7, 2014-10-02 13:19:49

Is it necessary to optimize variables in JAVA, and when?

For example, if we need to get the current year, we use calendar.get(Calendar.YEAR);
which returns a number in the int type. But it is clear that the short type will suffice for a year. Then you can cast the result to short, into a new short variable, or leave int, and, accordingly, create an int variable. Which way is correct?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vlad20012, 2014-10-02
@olexandr7

I wanted to first write this as a comment to the previous answer, but I decided that this answer is still not completely correct. Here the person asks rather "why do we need the byte and short types, if there is an int", and not "when to optimize". To the question "when to optimize" the answer is certainly correct.
Types with a bit width less than int should be used only from the point of view of saving memory, for example, in large arrays or classes with a large number of fields. It makes no sense to use them as local variables, because the processor operates on types the size of a machine word anyway (and Java doesn't work on 16-bit machines, does it?). Those. there is no question of optimization at all, there is no difference, and the types byte and short, in principle, should not appear as local variables. But if you have an array of over9000 elements, and short will also be used as elements, then int should not be used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question