Converter best practice for better performance

余生颓废 提交于 2020-01-07 06:33:06

问题


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;
    }

回答1:


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?




回答2:


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.)




回答3:


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.



来源:https://stackoverflow.com/questions/7347911/converter-best-practice-for-better-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!