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

查看:24
本文介绍了在 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 指向相同的地址,则 XOR 方法失败.第一个 XOR 将清除两个变量指向的内存地址处的所有位,因此一旦函数返回 (*a == *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.

维基页面上的更多信息:异或交换算法

More info on the Wiki page: XOR swap algorithm

虽然这个问题不太可能出现,但我总是更喜欢使用保证有效的方法,而不是在意想不到的时刻失败的聪明方法.

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天全站免登陆