Regex.CacheSize Property Gets or sets the maximum number of entries in the current static cache of compiled regular expressions.
The Regex class maintains an internal cache of compiled regular expressions used in >static method calls. If the value specified in a set operation is less than the current >cache size, cache entries are discarded until the cache size is equal to the specified >value.
By default, the cache holds 15 compiled static regular expressions. Your application >typically will not have to modify the size of the cache. Use the CacheSize property only >when you want to turn off caching or when you have an unusually large cache.
So I'd like to have insight into the current number of expressions in the cache. Anyone know if/how that is possible?
Idea being that I reuse < 15 of them now so don't want to fiddle with the CacheSize
, but would like to be able to check the actual cache usage at some point to either log if I am hitting the max (as regex usage expands) or dynamically adjust CacheSize
.
Alternatively, any comments as to the overhead of simply increasing the CacheSize
to some arbitrarily large number?
Decompilation (of mscorlib
4.0) reveals that the cache is an internal
linked list of CachedCodeEntry
, so you're not going to get at it without reflection.
The overheads of increasing the maximum cache size would be:
the memory cost of storing the cached entries; the usage of the maximum is simply in logic like this on Regex
creation:
2. the increased cost to traverse the cache looking for a match
So long as your numbers aren't absurd, you should be OK cranking it up.
Here's the reflection code you'd need to retrieve the current cache size:
public static int RegexCacheSize()
{
var fi = typeof(Regex).GetField("livecode", BindingFlags.Static
| BindingFlags.NonPublic);
var coll = (ICollection)(fi.GetValue(null));
return coll.Count;
}
We use the cast to ICollection
to avoid the complication of having to cast to a generic list on an internal type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With