java 交换数据

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

第一种方法比第二种有微弱优势,推荐第一种


个人博客:http://www.whereta.com

转载于:https://my.oschina.net/vincentzhao/blog/660504

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值