Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I MemoryCache a static object?

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?

like image 340
Cătălin Rădoi Avatar asked Oct 19 '25 12:10

Cătălin Rădoi


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.

like image 149
Marc Gravell Avatar answered Oct 21 '25 01:10

Marc Gravell