开发者

In java is boolean or integer arithmetic faster?

in Java is it faster to do an operation on two Booleans or two two integers? For example, is 1*1 or true&&false faster? What about doubles? In general what is the fastest primitive data type to work with? how does one f开发者_如何学Cind out how to measure the speed of these things?


If interesting I did such tests some time ago: The tests were like (with big amount 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


It will depend on the underlying architecture. In general, the fastest types will be the ones that correspond to your native word size: 32-bit on a 32-bit machine, or 64-bit on a 64-bit machine.

So int is faster than long on a 32-bit machine; long might be faster than int on a 64-bit machine, or the might be the same. As for boolean, I would imagine it's using the native word size anyway, so it will be pretty much exactly as fast as int or long.

Doubles (using floating point arithmetic) tend to be slower.

As long as you are dealing with primitive types, the difference will be negligible. The really slow types are the class types (like Integer or Boolean) -- avoid those if you want performance.


Primitives are faster than objects, the exact speed of primitive operations is going to depend on the JVM you're using (and assuming it JIT-compiles to native code, the native architecture you're running the JVM on), but 1*1 and true&&false are likely single machine instructions on modern architectures.

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


Generally those that use the auto-boxing mechanism of Java tend to be slower as the JVM have to convert the primitive type to the auto-boxed type.

This means that if you stick to primitives, you will tend to be faster than the objects that the JVM creates for you. Also, to measure, you could do something like that in pseudo code:

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

display time

That'll help you measure the time difference in your system, but it may or may not be the same across multiple systems.

Hope it helps :) Cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜