Is java logical or whole arithmetic faster?

in Java faster to perform an operation on two boolean or two integers? For example, 1 * 1 or true && false is faster? What about the doubles? In general, what does the fastest primitive data type work with? how to find out how to measure the speed of these things?

+4
source share
4 answers

This will depend on the underlying architecture. In general, the fastest types will be those that match the size of your native word: 32-bit on a 32-bit machine or 64-bit on a 64-bit machine.

So int faster than long on a 32-bit machine; long can be faster than int on a 64-bit machine, or it can be the same. As for boolean , I would suggest that it uses the native word size anyway, so it will be pretty much exactly as fast as int or long .

Doubles (using floating point arithmetic) is usually slower.

As long as you are dealing with primitive types, the difference will be negligible. Very slow types are class types (e.g. Integer or boolean ) - avoid the ones you need.

+3
source

If interested, I did such tests some time ago: The tests were similar (with lots of iterations):

 final int[] int_array=...; final boolean[] bool_array=...; etc. if (int_array[i]==67) ... if (bool_array[i]) ... if (float_array[i]==67.0F) ... etc. Time in seconds: Desktop(64bit Windows) Device (Android) bitmask 4.050 0.350 boolean 4.554-5.169 0.306-0.359 byte 0.583-0.915 0.263-0.293 char 0.587-0.814 0.280-0.329 short 0.583-0.914 0.280-0.290 int 0.548-0.949 0.288-0.338 float 0.824-1.129 0.965-1.035 long 0.646-1.054 0.480-0.509 double 0.828-0.971 1.138-1.214 
+4
source

Primitives are faster than objects, the exact speed of primitive operations will depend on the JVM you are using (and assuming that the JIT compiles your own code, the built-in architecture on which the JVM is running), but 1 * 1, and true && false is probably single machine instructions on modern architectures.

How to measure it? Code a test that calls an operation that you care about many times in the loop, and its time.

+2
source

Typically, those that use the Java auto-boxing mechanism tend to be slower, since the JVM must convert a primitive type to an auto-warp type.

This means that if you adhere to primitives, you will strive faster than objects created by the JVM for you. Also, to measure, you could do something like this in pseudocode:

 start timer do 10,000 operations on primitive/boolean stop timer display time 

This will help you measure the time difference in your system, but it may or may not be the same for multiple systems.

Hope this helps :) Greetings!

+2
source

All Articles