int a = 34423;
int b = 24345;
a = a ^ b;
b = b ^ a;
a = a ^ b;
如果采用常规算法:
int temp=a;
a = b;
b =temp;
计算效率:
测试方法
import org.freebencher.FbJobResult;
import org.freebencher.FbTarget;
import org.freebencher.Freebencher;
import org.junit.Test;
/**
* Vincent 创建于 2016/4/15.
*/
public class DemoTest {
@Test
public void swap() {
FbJobResult result = Freebencher.benchmark(new FbTarget() { //the behavior
public boolean invoke() {
int a = 34423;
int b = 24345;
test1(a, b);
// test2(a, b);
return true;
}
}, 20, // concurrency,
500000 // number of tests to run
);
System.out.println(result.report());
}
private static void test1(int a, int b) {
a = a ^ b;
b = b ^ a;
a = a ^ b;
}
private static void test2(int a, int b) {
int temp = a;
a = b;
b = temp;
}
}
第一种方法:
Test completed.
Disconnected from the target VM, address: '127.0.0.1:63459', transport: 'socket'
Concurrency: 20
Time taken for tests: 89801ms
Successful tests: 500000
Failed tests: 0
Tests per second: 5567.866727542009
Mean time per test: 4.4E-5ms
Percentage of the test finished within a certain time (ms)
50%: 0
60%: 0
70%: 0
80%: 0
90%: 0
95%: 0
98%: 0
99%: 0
100%: 2
第二章方法:
Test completed.
Concurrency: 20
Time taken for tests: 90237ms
Successful tests: 500000
Failed tests: 0
Tests per second: 5540.964349435376
Mean time per test: 3.0E-5ms
Percentage of the test finished within a certain time (ms)
50%: 0
60%: 0
70%: 0
80%: 0
90%: 0
95%: 0
98%: 0
99%: 0
100%: 1
第一种方法比第二种有微弱优势,推荐第一种