java 交换数据
博客专区 > 清尘V 的博客 > 博客详情
java 交换数据
清尘V 发表于2年前
java 交换数据
  • 发表于 2年前
  • 阅读 11
  • 收藏 1
  • 点赞 1
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

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

共有 人打赏支持
粉丝 44
博文 107
码字总数 47780
×
清尘V
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: