Why is a simple get-statement so slow?

亡梦爱人 提交于 2019-12-05 02:19:54

Introduction

I'd be willing to bet that the original code is so much slower because of a quirk in C# involving properties of type structs. It's not exactly intuitive, but this type of property is inherently slow. Why? Because structs are not passed by reference. So in order to access ray.Dir.x, you have to

  1. Load local variable ray.
  2. Call get_Dir and store the result in a temporary variable. This involves copying the entire struct, even though only the field 'x' is ever used.
  3. Access field x from the temporary copy.

Looking at the original code, the get accessors are called 18 times. This is a huge waste, because it means that the entire struct is copied 18 times overall. In your optimized code, there are only two copies - Dir and Pos are both called only once; further access to the values only consist of the third step from above:

  1. Access field x from the temporary copy.

To sum it up, structs and properties do not go together.

Why does C# behave this way with struct properties?

It has something to do with the fact that in C#, structs are value types. You are passing around the value itself, rather than a pointer to the value.

Why doesn't the compiler recognize that the get accessor is simply returning a field, and bypass the property alltogether?

In debug mode, optimizations like this are skipped to provide for a better debegging experience. Even in release mode, you'll find that most jitters don't often do this. I don't know exactly why, but I believe it is because the field is not always word-aligned. Modern CPUs have odd performance requirements. :-)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!