Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is calling a constructor faster then setting a field Mono?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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++

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading