Reputation: 1650
I need an advice on piece of 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?
Upvotes: 3
Views: 193
Reputation: 1062600
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.
Upvotes: 3
Reputation: 1466
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
Upvotes: 0
Reputation: 43513
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.
Upvotes: 1
Reputation: 46008
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.
Upvotes: 0
Reputation: 174299
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...
Upvotes: 1