Why are there both muti-object parameters and constructors?

Each so often (e.g. NUnit TestCaseData ), I see an object that has one or more constructors as follows:

 MyObject(object arg) MyObject(object arg1, object arg2) MyObject(object arg1, object arg2, object arg3) //guess they got tired of writing constructors? MyObject(params object[] args) 

If an object has a params constructor, however, what is the advantage of defining previous ones?

+5
source share
1 answer

This is usually for performance.

In your example, it is likely the case when MyObject is allocated with 1, 2 or 3 parameters, and therefore the developer is optimized for this. Firstly, the basic implementation can be optimized, and also parameters can be transferred on the call site without additional memory allocation. Using params , the compiler will need to insert the code to create the array, and then assign parameters to this array before calling it. If this is the norm for a call with 1, 2 or 3 parameters, you can avoid this distribution.

+6
source

Source: https://habr.com/ru/post/1207597/


All Articles