Speed of "if(object is type)" in C#
If I have a class with some value member that I want to store regardless of type, I would think that an object type would be the best. Lets say that the object can realistically be one of three types: string, int, customeClass. Would it be better to keep an extra enum member of the class with what type is stored in the value? Or is the execution of
if(object is string){.开发者_如何学编程..}
else if(object is int){...}
else if(object is customeClass){...}
fast enough that it's not worth storing the extra information?
Don't do premature optimization before measuring and proving that is
operator is a local bottleneck on a hot code path. Maintaining the enum for the alternative approach will tax development over long time.
With all respect...I think this is called premature optimization
. I wouldn't worry about the speed of an If
statement even if it is a loop of 10k+ iterations.
The performance of the IS test in .NET is rarely a performance problem - worst case is when the result is False and the object has a deep inheritance hierarchy. IS will have to perform multiple lookups going up the object's inheritance chain.
Unless your objects all have deep (100+) inheritance, the performance difference will be negligible.
The biggest difference between testing inheritance and testing an enum is that you can test an enum against multiple values in a switch statement. IS tests always require an if statement chain. The larger (> 10?) the number of elements to test, the greater the performance advantage of switch statements over if statements.
Creating a design where testing the type of the object is a key element of the design seems highly questionable. You should be trying to use polymorphism to allow you to manipulate various types without needing to know the type of each object. A virtual method call will be faster than testing inheritance or testing enums when the number of types involved is greater than 1.
This code will execute as fast as a cast (in other words it will be very fast as it is a single IL instruction). Retrieving an enum value from a property involves a lot more work (items must be pushed and popped from the stack and methods must be called) which would make it much slower than using is
.
All that being said, however, you shouldn't be concerning yourself with performance at this level until you have identified that this code is introducing performance issues. For most purposes this kind of optimization produces almost no measurable performance difference.
That will be fast enough. Storing any extra data would be uncessary as you'd have to lookup the properties of the instance of the class to get the type that you stored anyway if you did.
It is fast enough, it seems that you are doing a premature optimization which you shouldn't unless you've identified this as a bottleneck for your application performance.
精彩评论