Static vs member field revisited, need advice
I need an advice on piece o开发者_运维百科f functionality that I am ought to implement. The scenario is that we haven an HttpHandler which servers to intercept file uploads. In the handler, I need to persist a large dictionary of strings inside the memory. The dictionary might be as large as 100 entries. I am wondering whether it is safe to store that in a static variable, so that it is not initialized every time instance of the handler is created (there will be a lot of instance for sure). In general, what is the approach in such scenarios. Is it a generally better idea to use static fields, to persist data that will not be changed?
100 items in a dictionary isn't really very big - in fact, that is barely getting into the size where hashing is faster than linear search. If it will never change once initialized, then static may work - personally I try to have some other abstraction between static
and instance - for example a "context" or "configuration" class that I can pass into all the instances that need it. Then I can have multiple parallel configurations (if I need), but all the related instances can share a context/configuration - so no duplication.
IMHO a static field is just fine. You could initialize it at first use. Just make sure, you are using thread synchronisation.
You could also use a singleton, but I think, that would be a little bit overkill...
It's a good solution. Initialize the dictionary at the startup of your application(e.g. Global.asax) and it's ready for being read from since then.
You can override HttpHandler.IsReusable
and return false
in order not to have your handler recreated every time. You can then store the dictionary in local member.
Otherwise you need to use static variable.
Your dictionary doesn't seem to be big - 100 entries is peanuts. Unless each string is a few Megs long.
If your dictionary is going to be same for all the instances use static field otherwise use property field
If your data will not be changed then use Readonly variable
精彩评论