C# 'ref' keyword, performance

后端 未结 4 775
南笙
南笙 2020-12-06 11:15

If you have a Bitmap object that needs to be passed to numerous methods (about 10), and finally to an event where it shall finally be disposed of after it\'s used, would it

4条回答
  •  [愿得一人]
    2020-12-06 11:42

    Which type are you using exactly for holding the Bitmap? For example, System.Drawing.Bitmap is a reference type/class. When you pass a reference to a method (as an argument), the reference is passed by value. (A copy of the reference is made... not the object) So four bytes would be allocated on a 32-bit machine to hold the copy.

    Using the ref keyword has not much bearing on performance except that the same reference is passed (a copy of the reference is not made). It has the following benefits

    • Only clears the intent that the method taking the parameter may modify it, and the caller may get a modified value post execution.
    • And the variable must be initialized by the callee before being passed as an argument to the called function taking the ref parameter.

提交回复
热议问题