Bad Properties

Posted 3 CommentsPosted in Unity

Bad Properties

Most .Net programmers use properties whenever the opportunity arises. This is fully understandable but this good habit is bad for Unity.

In today’s post I will try to explain why you should avoid  properties in the unity engine.

What is a property and Benefits of using them

The usual way of public fields made them unsafe to be accessed (read and write) by any external class that had an access to them. So programmers have come up with a way to have access to a private variable with retain encapsulation. They called it Property.

In short it is special construction very often used in C # (And many other object-oriented languages).
 
Properties are not just to provide access to the fields; rather, they are supposed to provide controlled access to the fields of our class. As the state of the class depends upon the values of its fields, using properties we can assure that no invalid (or unacceptable) value is assigned to the fields.

The dark side of property

Ok, someone can say “Don’t worry about getter/setters slowing d own your code through indirection. The JIT has a thing called inlineing makes using the getter/setter just as efficient as direct field access.”

Everyone who uses Unity Engine knows that Update is the most commonly used function to implement any kind of game script.  Update is called every frame, if the MonoBehaviour is enabled. So even small allocations or calling another function (properties method)  every frame cause a GC spike in CPU. Unity has a efficient problem… 

Remember, the Update method should be used very carefully. Calmly. Property is not a taboo 😀  Property are  still very useful but they are used rarely.