# 交换a,b值的C#各种写法

public static void Swap1(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}

 .maxstack 1
.locals init (
[0] int32 temp)
L_0000: ldarg.0
L_0001: stloc.0
L_0002: ldarg.1
L_0003: starg.s a
L_0005: ldloc.0
L_0006: starg.s b
L_0008: ret


public static void Swap2(ref int a, ref int b)
{
a = a + b;
b = a - b;
a = a - b;
}

public static void Swap3(ref int a, ref int b)
{
a ^= b;
b ^= a;
a ^= b;
}

 .method public hidebysig static void Swap3(int32 a, int32 b)cilmanaged { .maxstack 8 L_0000: ldarg.0 L_0001: ldarg.1 L_0002: xor L_0003: starg.s a L_0005: ldarg.1 L_0006: ldarg.0 L_0007: xor L_0008: starg.s b L_000a: ldarg.0 L_000b: ldarg.1 L_000c: xor L_000d: starg.s a L_000f: ret } 

public static void Swap4(ref int a, ref int b)
{
b = a + 0 * (a = b);
}

.maxstack 8
L_0000: ldarg.0
L_0001: ldarg.1
L_0002: starg.s a
L_0004: starg.s b
L_0006: ret


（话说，我还不知道如何看C#生成的汇编指令，不知道哪个大牛告诉一下？）

位运算交换——慢。

temp交换——非常快。

诡异的交换——非常快。与temp不相上下，当然，百亿级的测试，还是temp微弱优势取胜。

posted @ 2012-08-07 21:36  primeli  阅读(3820)  评论(0编辑  收藏