WPF Singleton ValueConverters performance implications

1.1k views Asked by At

I have been consistently using Singleton value converters in WPF. But recently I got into an argument with a colleague where he was saying like it is bad to use singleton instance of valueconverters as they would be disposed only by the app domain unload. He was suggesting that singleton converters may come handy only in case of a page which is kept loaded until an application unload. Would really like to know views of WPF experts here.

EDIT (with example): I have a converter like

public class ABCConverter : IMultiValueConverter
{
    private static ABCConverter _instance;

    public static ABCConverter Instance
    {
        get { return _instance ?? (_instance = new ABCConverter()); }
    }

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return true;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        return false;
    }
}

I presently use it in xaml as

Converter="{x:Static conv:ABCConverter.Instance}"

Thanks in advance.

Raj

3

There are 3 answers

2
ColinE On BEST ANSWER

What you are arguing over here is a micro-optimisation. Unless your value converter is quite massive, the memory it consumes will be quite small.

Do not optimize prematurely. The 'standard' pattern for value converters is to create a new instance within each binding, i.e. avoiding singletons. If you do find yourself encountering memory issues, optimize at that point. Use profiling tools to determine where the issue is and target them specifically. I am willing to bet that your value converter will not be teh root cause of a memory issue.

0
Sankarann On

I my point of view, it is recommended to have value converters as Singleton since the converters might not have any local values and its just convert the values as desired values.

1
Mark Feldman On

There's no clear answer to this, it depends on your specific circumstances. If you're using a proper dependency injection framework (i.e. Ninject, Unity etc) then you can create an object in singleton scope without actually creating a singleton, you can even scope the converters to the life of particular object e.g. a parent window. Another thing you might want to look into is weak references, you get the performance benefits of a singleton but they get periodically cleaned up during routine GC if the app needs more memory.