int can be processed faster than short or byte

Asked 2 years ago, Updated 2 years ago, 28 views

When I was looking at the Java introduction, I found the following statement:

Computers these days have a lot of memory, so it's rare that these four models need to be used strictly.Also, int can be processed faster than short or byte, so if you want to substitute a integer, you can usually use the int type.

Why does it happen that things like short and byte that have less storage space are slower?

I'm probably optimizing something, but I'm worried because it's contrary to my intuition.

Also, is this not just a Java story, but is it the same languages?(c language, etc.)

java c

2022-09-29 22:55

3 Answers

It is not the language such as Java or C that determines the actual speed, but the processor that performs the operation.On the surface, the processor may support 8-bit/16-bit operations, but internally, it may still be truncated after performing operations at a larger value, such as 32-bit.Now that 32-bit/64-bit processors are common, it is safe to perform operations such as int.
Then, if you want to compute a large number of values, you should choose the appropriate minimum size, such as char or short, to reduce unnecessary memory access, but if not, int is still sufficient.

For x64, which is faster, 32-bit integer or 64-bit integer?See alsoEspecially, Egtra commented that 16bit operation is a little less efficient than 8bit/32bit operation on x86/x64 processors.
In addition, in C language, there is a concept of 8bit/16bit data type such as int_fast8_t and int_fast16_t (although x86/x64 Linux is not appropriate and is not actually very fast...)


2022-09-29 22:55

In terms of operations, many 32-bit CPUs can only do 32-bit operations (or most), meaning there are no 16/8-bit operational instructions. When performing operations on short or byte, additional instructions are generated to fit the results into the original type: byte

(The x86 can be 16/8 bit calculated and there are many, but the number of transistors cannot be reduced to maintain compatibility and the cost remains high.You shouldn't think this is standard.)


2022-09-29 22:55

(There may be many differences if we talk about details, but please understand the following as a conceptual story.)
For example, a 32-bit computer can handle 32-bit data.
Being able to handle 32-bit data means that you don't handle 8-bit data in four installments.
In other words, 32 bits are read in parallel when reading data from memory into registers (rather than being read in four batches at a time).
In this case, it is advantageous to process data in a 32-bit array from memory.
On the other hand, reading 1-byte (8-bit) data from memory in the same way requires adjustment depending on the byte position (four positions in 32-bit).
Therefore, it affects the speed of the extra operation.


2022-09-29 22:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.