Java has a lot of bit operations in the JDK, which is designed to make the code run faster, and we do an experiment to see how much computing time can be saved.
In the following code, the multiplication and bitwise operations were used to perform 100 million basic operations and print the time spent.
/** * Compare multiplication operation and bit operation time consumption gap */public class Testbitopr {public static void main (string[] args) {int j = 10; Long start = System.currenttimemillis (); for (int i=0;i<10000000;i++) {if (i% 2 = = 0) {for (int k=0;k<10;k++) {j = j*2; }} else {for (int k=0;k<10;k++) {j = J/2; }}} Long end = System.currenttimemillis (); System.out.println ("j=" +j+ "multiplication" Operation takes time: "+ (End-start) +" MS "); j = 10; Start = System.currenttimemillis (); for (int i=0;i<10000000;i++) {if (i% 2 = = 0) {for (int k=0;k<10;k++) {j = j<<1; }} else {for (int k=0;k<10;k++) {j = j>>1; }}} end = System.currenttimemillis (); System.out.println ("j=" +j+ "bit operation takes time:"+ (End-start) + "MS"); }}
1. Execute the above code on my notebook and get the following time:
j=10 multiplication operation takes time: 548msj=10-bit operation takes time: 115ms
2. Execute this code on the mobile device and get the following time:
j=10 multiplication operation takes time: 3544msj=10-bit operation takes time: 928ms
Summarize:
In the case of large computational volume, the bit operation can save CPU time greatly, and the consumption time of multiplication operation is 3.5~5 times of bit operation.
The time spent on the mobile device is 7~10 times on the PC, you can see the mobile device CPU and computer CPU gap is still relatively large, on the mobile device time savings also indicates that the battery can be used longer, so mobile devices need to optimize the better code.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Comparison experiment of bit operation and multiplication operation