开发者

.NET Regex Instance Caching

I've read this article, which describes how instance vs static methods get called with a .NET regex.

However, what about if the variable itself is static? Does anyone know if .NET does any sort of caching that could potentially cause a memory leak?

Clarification. For example:

public static Regex Foo = new Regex(@"(?:,.*)");

versus:

public static void MyMethod(){
  Regex Foo = new Regex(@"(?:,.*)");
}

Is either of those more likely to cause any memory issues than the other? I know the second one will obviously create more instances, but does the first one h开发者_Python百科ave any sort of caching of incoming strings to worry about, since it will essentially sit around forever.


If you have an instantiated Regex object and you are only calling instance methods on it, then cacheing (according to the supplied article) will not occur. If you create the Regex object and store it as a static property in your class, you are still dealing with an instantiated object, hence the cacheing will not occur (>=.net 2.0).

On the other hand, every time you call Regex static methods, such as Regex.Match("bla","bla"), the parsed and compiled regular expressions will be cached.

EDIT

Looking at your example, cacheing will not occur in either case. If however, the second example was:

Match m=Regex.Match(@"(?:,.*)",someString);

... then the compiled regular expression (?:,.*) will be cached, so you can efficiently make subsequent calls to Regex.Match(@"(?:,.*)",... without needing to reparse/recompile the expression (?:,.*). I guess in terms of memory consumption, this would equate almost exactly to keeping a static instance. On the other hand, if the regular expression supplied to Regex.Match changed, then an additional entry would be made at some (probably negligible) expense.


There's no such thing as a "static instance" - there are just static variables which refer to objects. The same object can be referred to by an instance variable, a local variable or a static variable. It won't change any of the code within the Regex constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜