2

I know there is a couple answered questions on here regarding "request scoped" globals, but I want to nit-pick on something specifically and maybe squeeze some extra enlightenment out of one or two of you.

I have an ASP.NET C# Website and a static Dictionary of objects (loaded from DB once on Application start). Each page request will need to do a lookup in the Dictionary (based on a key derived from the request url/etc) and get the appropriate object.

The issue is I'm trying to maximize efficiency by reducing the lookups to the Dictionary per Request. Doing just a single lookup within a Page itself is easy enough and I can pass the object to sub controls, etc too.. but global.asax is separate from the Page and it also needs to use the object (in Application_BeginRequest and Session_Start).

So is doing a Dictionary lookup once in Application_BeginRequest, once (when necessary) in Session_Start and once in the Page negligible speed wise, even if there are many requests coming in every second?

I would like it if I could just have a Request scoped global variable that I can easily call upon.. the only one I see available though is HttpContext.Current.Items and that is a Dictionary itself.

Am I being ridiculously nit-picky with my concern over efficiency? or will these milliseconds (nanoseconds?) get me in the long run when more and more requests are being made?

Thanks.

PS. I currently only have around 100 objects in the Dictionary although this may increase in the future.

devlop
  • 1,168
  • 1
  • 8
  • 19

2 Answers2

2

A dictionary lookup is (roughly) a constant-time operation, so, yes, I do believe that you are trying to over-optimize here.

As always, when performance is an issue, try to do profiling (there are tools available for this) before doing micro-optimization. Otherwise, you might end up wasting time on optimizing the wrong parts of your application.

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
2

I think it's not worth trying to optimize it even more, imagine a Dictionary implemented with super fast find method ( tree, btree or whatever else ).

in fact if you have 100, 200 or 10.000 objects it would take so very little to find the proper value when searching by key that you probably would not notice any difference.

Davide Piras
  • 43,984
  • 10
  • 98
  • 147