Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array elements by ref [duplicate]

Tags:

c#

Possible Duplicate:
C# parameters by reference and .net garbage collection

I was thinking of using ref arguments to limit the bounds checking of an array. For example the code of swapping two elements is :

class Test {
  int[] array;

  private void qSort() {
    ...blah...
    int temp = array[a];
    array[a] = array[b];
    array[b] = temp;
  }
}

which has 4 access to the array the alternative will be :

class Test {
  int[] array;

  private void qSort() {
  ...blah...
    Swap( ref array[a], ref array[b] );
  }

  static void Swap(ref int a,ref int b) {
    int temp = a;
    a=b;
    GC.Collect();  // suppose this happens
    b=temp;
  }
}

which theoretically has only 2 access to the array

What confusing me is that I don't know what exactly happens when I pass an array element by ref. If Garbage Collector kicks in, while executing code in the Swap function, will be able to move the array ? or the array is pinned for the duration of the call ?

Mind that the above code is a simple test case. I want to use it in much more complex scenarios

Edit: As BrokenGlass pointed out, this is answered by Eric Lippert here C# parameters by reference and .net garbage collection

The array will not be pinned and GCollector can move it and will update accordinly any ref to an element of it, that resides on the stack

like image 882
Panos Theof Avatar asked Oct 18 '11 12:10

Panos Theof


1 Answers

The Swap function still access the array 3 or 4 times, the Swap function does not offer any performance adavantage over the simpler code. It might be useful if it is reused.

static void Swap(ref int a, ref int b) 
{     
    int temp = a;  //<-- Here, a is in the array
    a=b;           //<-- a and b are in the array
    b=temp;        //<-- b is in the array
}

The garbage collector will not release memory you have a reference to, as happens when you pass by reference.

like image 75
Jodrell Avatar answered Oct 11 '22 00:10

Jodrell