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开发者_JAVA百科 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?
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.
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));
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!)
精彩评论