Omer van Kloeten's .NET Zen

Programming is life, the rest is mere details

News

Omer van Kloeten's Facebook profile

Omer has been professionally developing applications over the past 8 years, both at the IDF’s IT corps and later at the Sela Technology Center, but has had the programming bug ever since he can remember himself.
As a senior developer at NuConomy, a leading web analytics and advertising startup, he leads a wide range of technologies for its flagship products.

Get Firefox


powered by Dapper 

.NET Resources

Articles :: CodeDom

Articles :: nGineer

Culture

Projects

CodeDom Tip: Cache Reusable Objects

Because CodeDom is so verbose and uses a massive grid of objects to represent code structures, it also has many small reusable objects, such as CodeTypeReference objects. Many people overlook this fact because there are so many object being created anyway, but sometimes a certain object will be used over and over. Since both the creation of these objects takes time and they also take up memory as unnecessary copies, consider creating a cache.

For example, for the next release of the CodeDom Patterns library, I've created a cache for CodeTypeReference objects:

using System; using System.Collections.Generic; using System.CodeDom; namespace DotNetZen.CodeDom { /// <summary> /// Acts as a cache for <see cref="CodeTypeReference"/> objects. /// </summary> public static class CodeTypeReferenceStore { private static Dictionary<RuntimeTypeHandle, CodeTypeReference> typeReferences = new Dictionary<RuntimeTypeHandle, CodeTypeReference>(); private static Dictionary<string, CodeTypeReference> nameReferences = new Dictionary<string, CodeTypeReference>(); /// <summary> /// Gets a <see cref="CodeTypeReference"/> by the <see cref="Type"/> it should reference. /// </summary> /// <param name="type">The type being referenced.</param> /// <returns>A <see cref="CodeTypeReference"/> object.</returns> public static CodeTypeReference Get(Type type) { RuntimeTypeHandle handle = type.TypeHandle; if (!typeReferences.ContainsKey(handle)) { typeReferences.Add(handle, new CodeTypeReference(type)); } return typeReferences[handle]; } /// <summary> /// Gets a <see cref="CodeTypeReference"/> by the name of the <see cref="Type"/> it should reference. /// </summary> /// <param name="type">The name of the type being referenced.</param> /// <returns>A <see cref="CodeTypeReference"/> object.</returns> public static CodeTypeReference Get(string typeName) { if (!nameReferences.ContainsKey(typeName)) { nameReferences.Add(typeName, new CodeTypeReference(typeName)); } return nameReferences[typeName]; } } }

Comments

Jason Haley said:

# October 26, 2006 10:35 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)