Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Factories #218

Closed
MehdiK opened this issue Apr 15, 2014 · 3 comments
Closed

Improve Factories #218

MehdiK opened this issue Apr 15, 2014 · 3 comments

Comments

@MehdiK
Copy link
Member

MehdiK commented Apr 15, 2014

We have a few factories in the codebase in charge of returning an instance of a class based on the ambient culture. Here is an example of a factory:

    private static readonly IDictionary<string, Func<IFormatter>> FormatterFactories =
        new Dictionary<string, Func<IFormatter>>(StringComparer.OrdinalIgnoreCase)
    {
        { "ro", () => new RomanianFormatter() },
        { "ru", () => new RussianFormatter() },
        { "ar", () => new ArabicFormatter() },
        { "he", () => new HebrewFormatter() },
        { "sk", () => new CzechSlovakPolishFormatter() },
        { "cs", () => new CzechSlovakPolishFormatter() },
        { "pl", () => new CzechSlovakPolishFormatter() }
    };

    private static IDateTimeHumanizeStrategy _dateTimeHumanizeStrategy = new DefaultDateTimeHumanizeStrategy();

    public static IFormatter Formatter
    {
        get
        {
            Func<IFormatter> formatterFactory;
            if (FormatterFactories.TryGetValue(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, out formatterFactory))
                return formatterFactory();

            return new DefaultFormatter();
        }
    }

Basically every time we call Formatter, which is quite frequent, we're creating a new instance for the Formatter/NumberToWordsConverter/Ordinalizer, and this is quite bad.

We need to change the factory to return a lazy instance instead so it's created on the first call and available from then on.

@hazzik
Copy link
Member

hazzik commented Apr 15, 2014

But creation of these classes is really cheap.

UPD it seems that creation of the stateless class is much faster than using Lazy<>

@MehdiK
Copy link
Member Author

MehdiK commented Apr 15, 2014

The creation will be cheap; but using Humanizer on a website with many calls to localised methods will create so many objects in memory. These will be eventually GCed; but do we really need 1000s of these classes in memory?

@MehdiK
Copy link
Member Author

MehdiK commented Apr 27, 2014

Fixed in #243

@MehdiK MehdiK closed this as completed Apr 27, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants