optimization of type comparison
-
I'm overriding an Equals() method in .NET which a type specialization in mind but don't want to kill my code in stupid ways. So: public override bool Equals(object obj) { if ( obj.GetType() == typeof(double) ) // foo else return base.Equals(obj) } The line to optimize is "if ( obj.GetType() == typeof(double) )". The constant typeof(double) calls is a waste. Tried "if ( obj.GetType().Name == "System.Double" )" with horrible results. Any optimizations out there? Thx!
-
I'm overriding an Equals() method in .NET which a type specialization in mind but don't want to kill my code in stupid ways. So: public override bool Equals(object obj) { if ( obj.GetType() == typeof(double) ) // foo else return base.Equals(obj) } The line to optimize is "if ( obj.GetType() == typeof(double) )". The constant typeof(double) calls is a waste. Tried "if ( obj.GetType().Name == "System.Double" )" with horrible results. Any optimizations out there? Thx!
You could store the result of this call to a variable that's used by the comparison.
Christian Graus - C++ MVP 'Why don't we jump on a fad that hasn't already been widely discredited ?' - Dilbert
-
I'm overriding an Equals() method in .NET which a type specialization in mind but don't want to kill my code in stupid ways. So: public override bool Equals(object obj) { if ( obj.GetType() == typeof(double) ) // foo else return base.Equals(obj) } The line to optimize is "if ( obj.GetType() == typeof(double) )". The constant typeof(double) calls is a waste. Tried "if ( obj.GetType().Name == "System.Double" )" with horrible results. Any optimizations out there? Thx!
if (obj is double) ... else ...
Luc Pattyn
-
if (obj is double) ... else ...
Luc Pattyn
if (obj is double) wins! Gives me 2x speed over obj.GetType() == typeof(double). Thanks!
-
if (obj is double) wins! Gives me 2x speed over obj.GetType() == typeof(double). Thanks!
As far as performance goes, there are only two rules: 1) shorter code is always faster 2) rule 1 is false :)
Luc Pattyn
-
As far as performance goes, there are only two rules: 1) shorter code is always faster 2) rule 1 is false :)
Luc Pattyn
I didn't think that 'is' would work for a value type ? Or is that just 'as' that won't work ( as it can't return null ) ???
Christian Graus - C++ MVP 'Why don't we jump on a fad that hasn't already been widely discredited ?' - Dilbert
-
I didn't think that 'is' would work for a value type ? Or is that just 'as' that won't work ( as it can't return null ) ???
Christian Graus - C++ MVP 'Why don't we jump on a fad that hasn't already been widely discredited ?' - Dilbert
Sure is is always OK (it produces a bool) whereas as is not. :)
Luc Pattyn