开发者

Converter best practice for better performance

I'm using WPF converter and wondered in terms of performance what would be better in the following example, to use class members or local variables ?

    public object Convert(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
    {
        if ((int)value == 1)
           开发者_开发百科 return (Color)ColorConverter.ConvertFromString("#FCD44E");

        return (Color)ColorConverter.ConvertFromString("#FCD44E");
    }

or :

    Color _color1 = (Color)ColorConverter.ConvertFromString("#FCD44E");
    Color _color2 = (Color)ColorConverter.ConvertFromString("#FCD666");

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((int)value == 1)
            return _color1;

        return _color2;
    }


The most performant would be to use private static readonly as follows

private static readonly Color Color1 = (Color)ColorConverter.ConvertFromString("#FCD44E");
private static readonly Color Color2 = (Color)ColorConverter.ConvertFromString("#FCD666");

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if ((int)value == 1)
        return Color1;

    return Color2;
}

See this answer for good discussion: Method can be made static, but should it?


While performance-wise the only relevant thing is to not do the conversion in every call to the Convert-method (as has been shown explicitly in the other answers), i would never write such a hard-coded converter in the first place, if you can parameterize something, do not hesitate to do so, e.g.:

public class OnValueToColorConverter : IValueConverter
{
    public int Value { get; set; }
    public Color OnValueColor { get; set; }
    public Color OffValueColor { get; set; }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (int)value == Value ? OnValueColor : OffValueColor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
<vc:OnValueToColorConverter Value="1"
                            OnValueColor="#FCD44E" 
                            OffValueColor="#FCD666" />

(For this sort of thing one would normally not use a converter by the way but a Style with a default setter and a DataTrigger for the value on which it should change.)


The second option, but use static readonly fields if those colors are always constant. That way you're doing the work once, not every time you create a converter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜