1. 程式人生 > >交換a、b的值temp = a; a = b; b = temp;比a = a^b;b = a^b;a = a^b;快

交換a、b的值temp = a; a = b; b = temp;比a = a^b;b = a^b;a = a^b;快

先看程式碼,交換a、b的值十億次
<span style="font-size:14px;">		int a=222;
		int b=111;
		
		int size = 1000000000;
		int temp=0;
		long start = System.nanoTime();
		
		for (int i = 0; i < size; i++) {
			temp = a;
			a = b;
			b = temp;
		}
		System.out.println("用時ns:"+(System.nanoTime()-start));
		
		a=222;
		b=111;
		start = System.nanoTime();
		
		for (int i = 0; i < size; i++) {
			a = a^b;
			b = a^b;
			a = a^b;
		}
		System.out.println("用時ns:"+(System.nanoTime()-start));</span>

執行結果(納秒):

用時ns:996150
用時ns:1769620

發現使用賦值交換比位運算交換兩個數的值要快將近一倍。