1

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?

3
  • 1
    watch this [stackoverflow.com/questions/552731/… Commented Jun 14, 2011 at 4:35
  • 1
    next time pls try not to totally modify question after 40 min, ask new one ;P Commented Jun 14, 2011 at 5:00
  • 2
    It makes no difference, the x64 jitter in particular generates the exact same code for both. As it should. Don't sweat the small stuff. Commented Jun 14, 2011 at 5:06

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe not express myself well, question fixed, sorry
2

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.