logo search
Учебник_ПОА

Performance issues

Let's dig a little deeper. When data is passed into methods as value type parameters, a copy of each parameter is created on the stack. Clearly, if the parameter in question is a large data type, such as a user-defined structure with many elements, or the method is executed many times, this may have an impact on performance.

In these situations it may be preferable to pass a reference to the type, using the ref keyword. This is the C# equivalent of the C++ technique of passing a pointer to a variable into a function. As with the C++ version, the method has the ability to change the contents of the variable, which may not always be safe. The programmer needs to decide on the trade-off between security and performance.

int AddTen(int number) // parameter is passed by value

{

return number + 10;

}

void AddTen(ref int number) // parameter is passed by reference

{

number += 10;

}

The out keyword is similar to the ref keyword, but it tells the compiler that the method must assign a value to the parameter, or a compilation error will occur.

void SetToTen(out int number)

{

// If this line is not present, the code will not compile.

number = 10;

}