什么是用C来交换价值的最快方法? [英] What is the fastest way to swap values in C?

查看:103
本文介绍了什么是用C来交换价值的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想交换两个整数,我想知道这两个实现会更快:
与一个临时变量明显的方式:

I want to swap two integers, and I want to know which of these two implementations will be faster: The obvious way with a temp variable:

void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

或者异或版本,我相信大多数人都看到:

Or the xor version that I'm sure most people have seen:

void swap(int* a, int* b)
{
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

这似乎是第一个使用一个额外的寄存器,但第二个是做了三加载和存储,而首只完成两个各自的。谁能告诉我这是更快,为什么?在为什么是更重要的。

It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each. Can someone tell me which is faster and why? The why being more important.

推荐答案

异或方法失败,如果A和B指向同一个地址。第一异或将清除所有的位在存储器地址指向的两个变量,所以一旦函数返回(*一个== * B == 0),而不管初始值的

The XOR method fails if a and b point to the same address. The first XOR will clear all of the bits at the memory address pointed to by both variables, so once the function returns (*a == *b == 0), regardless of the initial value.

在Wiki页面上更多信息:
XOR算法交换

More info on the Wiki page: XOR swap algorithm

尽管这不太可能,这个问题就上来了,我总是preFER使用有保证的工作,而不是失败在意想不到的时刻聪明的方法的方法。

Although it's not likely that this issue would come up, I'd always prefer to use the method that's guaranteed to work, not the clever method that fails at unexpected moments.

这篇关于什么是用C来交换价值的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆