开发者

Is swap method in C# whose parameters have value type not efficient?

Che开发者_如何学Gock this method:

public static void Swap(ref int i, ref int j)
{
   int aux=i;
   i=j;
   j=aux;
}

Is it more efficient than this?

public static void Swap1(int[] a, int i, int j)
{
   int aux=a[i];
   a[i]= a[j];
   a[j]=aux;
}

I'm using these methods like this:

static void Main(string[] args)
{
    int[] a = { 5, 4, 3, 1 };
    Swap(a[1], a[2]);
    Swap(a, 1, 2);
}

Which of these methods is more efficient and why?


Your method will not swap any parameters at all. I mean it will swap parameters inside your method, but it will not affect the values of source parameters. That's because value types are copied when they are passed into methods. Here's the example:

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

void HereHappensNothing()
{
    int a = 1;
    int b = 2;
    IncorrectSwap(a, b);
    // a still = 1, and b = 2, nothing happens
}

To make your method work you have to pass value types by reference like that:

void CorrectSwap(ref int a, ref int b)
{
    int temp = a;
    a = b;
    b = temp;
}

void HereSwapHappens()
{
    int a = 1;
    int b = 2;
    CorrectSwap(ref a,ref b);
    // a = 2, and b = 1, Ok.
}

Here you can read about value types and how to work with them.

Update

Following your update. I don't think there should be any significant difference in performance as long as value types don't get boxed when passed by ref. There can be some penalty when you pass more parameters, but I don't think it should be significant, you will not see the difference.


Not passing by ref will not work. As you will only be affecting the local parameters.


Your code does nothing! When parameters are passed by value you can't change them. So to correctly implement Swap you need to pass by ref.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜