ternary operator imbrication
-
27-09-2019 - |
Question
I am wondering: what is the best instruction in terms of performance between those 2 versions:
Background = Application.Current.Resources[condition ? BackgroundName1 : BackgroundName2] as Brush;
and:
Background = condition ? Application.Current.Resources[BackgroundName1] as Brush : Application.Current.Resources[BackgroundName2] as Brush;
is there any difference? and if yes, wich one is better?
thanks
NB: BackgroundName1 & 2 are simply strings
Solution
The first one is shorter and more readable.
It's also easier to maintain.
If you later change it to read a different Resources dictionary, you might forget to change the second half of the second one.
The first one is also more clearly reading from the same dictionary.
OTHER TIPS
First: Use a profiler to find the slowest thing. If you're having a performance problem it doesn't make sense to spend hours or days working on making something faster that is already fast enough.
Second: You can determine the answer to your question by trying it both ways and carefully measuring to see if there is a difference. Don't ask us which is faster; we don't know because we haven't tried it and have no ability to try it.
Don't get too caught up in micro-optimizations! The performance gain you'll get will be nil. Go for the code that is more readable and easier to understand in the end.
No difference whatsoever.