Check 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:
To make your method work you have to pass value types by reference like that:
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.