Should I MemoryCache a static object?

Viewed 439

I have a static class with a static List inside of it.

public static class Translations {
    public static List<string> Resources {get; set;}
}

Does it make sense to MemoryCache that List? Or by being static is already kept in memory, the same list for all users and there's no need to memcache it?

1 Answers

If we're talking about in-process memory, then a static field will have exactly the same lifetime as anything in MemoryCache.Default, but the field will be more direct, and therefore faster. The bigger problem, however, is the race condition if you ever mutate the contents of the list after it has been assigned, since multiple threads could be looking at the data at the same time (bad things). It is probably a good idea to use some kind of immutable collection (ImmutableList<T>, for example), to avoid any complications there.

Related