Thomas
Thomas

Reputation: 3854

Is passing value types by ref more performant for large iterations?

For example:

void Foo(ref int x, ref string s, ref MyStruct ms)
{ // Do stuff with them }

Consider this function to be called a large number of times such as 50000+ times. There's memory accessing, allocation, and garbage collection happening, and I don't know if or at which point you would see a performance gain, in terms of speed, by passing by ref in this type of example.

Upvotes: 0

Views: 76

Answers (1)

John V
John V

Reputation: 1364

Passing by ref can really help if you are passing structs. It's easy to forget that structs are value types, so when you call a function with a struct, the function operates on a copy of the struct. Depending on the size of the struct and the number of calls this could be a huge performance impact. I recently worked on some image processing code that did a lot of work with the Point struct. By passing the struct by ref I got a huge performance increase.

Also depending on the version of the language you're using, you can also pass parameters using in which means to pass a reference, but don't let the function change it.

Upvotes: 1

Related Questions