views:

34

answers:

3

In a specific piece of code i cal Type.GetFields() many times. One call can call it 5 times or more. Also a piece of code could iterate thousands of times. ATM i dont need to optimize but i am asking so if i need to i know how.

How could i cache this? I am hoping i can do something like obj.GetType().Tag["myCacheId"] and pull out cached data. But i doubt i can do this. Can i attach data to a type somehow? i really hope i dont resort to a singleton. How might i cache data relating to Type's?

A: 

Just stick it in a FieldInfo[] somewhere, like at the beginning of your method or before your loop:

FieldInfo[] fields = Type.GetFields((BindingFlags.Public | 
    BindingFlags.Static | BindingFlags.Whatever));
SoloBold
+3  A: 

The CLR already caches metadata. Very slow on the first call when it is dug out of the assembly, fast afterward. Caching yourself isn't going to make any difference.

Hans Passant
While true, you can often still improve it by eliminating the method calls.
codekaizen
I heard this once but it wasnt cleared to me what was cached. If its the metadata i touch then great =). I'll do a test when i really need to. Now thinking about it my code should be fast enough.
acidzombie24
A: 

If you have many Types, you could use a Dictionary to map from each type to the cached information for that type. (But this will only help if the dictionary lookup is faster than the Type.GetFields operation!)

Jason Williams