C# 'ref' keyword, performance

后端 未结 4 781
南笙
南笙 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:39

    The 'ref' doesn't pass the object itself into the function, instead it passes a reference to the variable it is stored in/at.

    If the object is a class or an interface, then whenever you access that variable in the function, it has to dereference it, and then access the variable. If it was passed in without the 'ref' keyword, then it wouldn't have to do the dereference step (thus it will be slightly faster).

    If the object is a struct (or enum or other base type), the 'ref' keyword passes a reference to the variable that stores the struct, which still causes the SLIGHT speed hit of dereferencing whenever you use it, but if you don't specify it, then the program has to allocate memory for a new instance of the struct and then copy it. In most cases, it is faster to pass structs via the ref keyword, but this may not be the case if it is a really small struct, or if it's dereferenced a lot (and I mean a LOT).

    So if you are passing a struct, then ref is usually the way to go, otherwise there won't really be much of a difference (the overhead in the dereferencing phase is minuscule).

    Oh, and to actually answer the question, a Bitmap is a class, so the 'ref' keyword won't really make a speed difference over a non-'ref' parameter.

提交回复
热议问题