A property occupies space in the object?

Asked

Viewed 126 times

9

I was reading a question about properties and saw that she is at the same time one or two methods.

Do you have any additional cost in memory and processing in using it? If you don’t use the code you can get more optimized?

1 answer

6


The property itself is a method, or a pair of methods get and set. Then, like any method, a memory space is occupied for the method code once in the application, no matter how often it is used. It is something very small and practically can be disregarded.

Like every method, there is a code execution and there is a processing cost that depends on what will be executed. Even an empty method has some cost, if not optimized.

So if you’re just assigning or picking up a value there’s a overhead compared to doing it right in the field.

If you want to know if it occupies a space in the instance, no, the property itself does not occupy. But it’s very common for it to access a field, it’s actually possible that it encapsulates that field. The field space creates a cost on the object, but if the property does not have a linked field there is no cost.

Just note that this

public int prop { get; set; }

by definition has a field associated with itself that does not appear in the code, so this field will take up space. In this example as it is a int will take 4 bytes.

Already

public bool prop { get => status > 0; }

has no direct field, so does not occupy anything else. Of course this field status is a field that will occupy a space, but it is not tied to the property prop, this property does not create overhead in the object.

Note that the property can facilitate maintenance and versioning, but it imposes a processing cost no matter how simple. In general it is good to use, but if you need much of the best possible performance the access to the direct field can be better, so it does not call any extra code. Have a question to better understand the advantage of using a property to encapsulate a field.

using static System.Console;

public class Program {
    public static void Main() {
        var objeto = new Classe(1);
        WriteLine(objeto.IsFree);
    }
}

public class Classe {
    public Classe(int x) => status = x;
    private int status; //aqui ocupa 4 bytes
    public bool IsFree { get => status > 0; } //aqui nada ocupa na instância
    public int Id { get; } = 0; //aqui ocupará 4 bytes porque tem um campo implícito
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.