Is it possible to check the number of cached regex?

前端 未结 1 1531
一整个雨季
一整个雨季 2021-02-20 07:00

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

1条回答
  •  没有蜡笔的小新
    2021-02-20 07:34

    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:

    1. the memory cost of storing the cached entries; the usage of the maximum is simply in logic like this on Regex creation:

      • are we caching, in general?
        • if so, cache this regex
        • have we now exceeded the maximum cache size?
          • if so, remove the last cache entry


    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.

    0 讨论(0)
提交回复
热议问题