Home > Back-end >  Is calling a constructor faster then setting a field Mono?
Is calling a constructor faster then setting a field Mono?

Time:01-22

I'm working on implementing Mono to my C project and I have a C# class that holds a single integer. Something like this:

public class TestClass {
    int number;
}

And I have another Class that has a field of TestClass. Something like this:

public class AnotherClass {
    TestClass test;
}

Now, I have an instance of AnotherClass called instance and I want to set it's test field. Since the field can be null by default I create an instance of TestClass called testInstance, set it's number field and then set instance.test field to testInstance.

However I'm wondering if it wouldn't be faster to instead give TestClass a constructor that sets the number field to a parameter it takes and then initialize testInstance with that constructor and lastly set instance.test to testInstance. So my questions is that, Is it faster to call a constructor that just sets a field from withing C# or to set that field manually from within C

CodePudding user response:

Performance difference should be very small in your case, It may be big when your constructor has complex code inside it or multiple fields to be set. In general, it's good to practise keeping the constructor simple and doing the object initialization inside it.

When you are setting the field directly not in the constructor you are escaping from doing the things which the constructor does apart from setting this particular field.

your code should be readable, easily maintainable and scalable, so chose the approach accordingly.

If you are really concerned about the performance then you could do a benchmark and compare the results.

  • Related