Direct parameter Vs passing a class
Assume that there is a class with 3 attributes.
Employee
- Name
- Age
- Sal
I have a webmethod, GetInfo
.
Does it make any difference with regard to performance for passi开发者_Go百科ng direct param vs. direct classs?
GetInfo(Employee emp) // This will internally call emp.age & return the values.
GetInfo(int age)
Any thoughts?
Measure the performance for yourself to determine if one performs better than another. Create dual methods, get an instance of Stopwatch, and perform a few thousand calls to each version of the method and see if there is a demonstrable, relevant difference between the two. I doubt there is.
In the meantime, ask yourself if the Employee
instance is even relevant to the method. If all are you doing is taking the employee's age and then passing back data that is unrelated to the specific employee, then why bother tying the method to an instance? Just take the integer parameter. For example, let's say your method call was this
public Employee[] GetEmployeesByAge(ArgumentType argument)
Does it make sense for the parameter to be an Employee
or a simple integer? The relevant input is the age, not the Employee
from which the age originated. If you opted to use the Employee
as the parameter, you're limiting this method to callers that already have an instance of Employee
standing by, which might not always be the case. (After all, they're trying to get the employees.)
Choose your guideline: YAGNI, KIS, etc.
The performance is probably not noticeable.
// Either way the performance is about the same
Employee emp = new Employee();
Info out1 = GetInfo(emp);
// or
Info out2 = GetInfo(emp.Age);
The only consideration you will need to make regarding performance, is if you already have the Employee
class or not. If you have to create an empty Employee
object with the age set then just use the age.
Semantically, however, it should be made obvious (by the method name) that you are retrieving by age if you take an int
parameter as otherwise it may not be obvious what you are sending, unless you look at the method declaration, so consider changing the name to GetInfoByAge
.
I think you should use the method that requires exactly what it needs, and no more. This would improve code reuse and separation of concerns. The performance hit shouldn't be a concern at this stage of development.
精彩评论