Fisher
Fisher

Reputation: 1794

C# structs returned by method performance

Lets say that i have a struct like that:

public struct MyCustomDataset : IEnumerable<float> {
    public float v1;
    public float v2;
    public float v3;

    public MyCustomDataset(float v1, float v2, float v3) {
        this.v1 = v1;
        this.v2 = v2;
        this.v3 = v3;
    }

    // Enumerable impl
    public IEnumerator<float> GetEnumerator() {
        yield return v1;
        yield return v2;
        yield return v3;
    }
    IEnumerator IEnumerable.GetEnumerator() {
        return GetEnumerator();
    }
}

And methods like this:

public static MyCustomDataset test() {
    return new MyCustomDataset(1,2,3);
}

public static void test2() {
    MyCustomDataset ds = test();
    /* doing stuff with ds */
}

I want to know if its more optimal then if MyCustomDataset was class instead of struct. I need to know that, because im calling test() in apps main loop, so MyCustomDataset is going to be allocated in every apps iteration. Because of that, i wont make MyCustomDataset an class, because it would be like performance suicide. Im cosidering using struct, because im suspecting that it can behave more or less like primitive type in that case.

Would it be ok with performance ?

Im not going to assign MyCustomDataset to any class field, I will only read it in methods body, and maybe will pass it into a few method calls, so it will be present in few local scopes.

Upvotes: 0

Views: 290

Answers (1)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

You:

because it would be like performance suicide

Why do you think so? What difference between structs and classes are you refering to?

I think you should go with a struct if you feel it's more or less like "a primitive type" (your words). This is just three float values (possibly a total of 96 bits), so it's small enough for a value type. But if you stick to a struct, make the fields readonly.

Upvotes: 2

Related Questions