Static vs. Instance Regex

Editor
Jun 24, 2011 at 1:14 PM

Looking in the code I found that an instance regex is created each time. As MS Documentation states Static regular expression methods are recommended as an alternative to repeatedly instantiating a regular expression object

I'm agree with that and vote for static regex. What about you?

Editor
Jul 11, 2011 at 2:58 PM

Instance Regex replaced with static one

Coordinator
Jul 13, 2011 at 4:32 PM

I'm not entirely convinced this is the best solution, but given the frequency the RegEx is used, it is unlikely to make a noticeable difference to the user.

My understanding is that using a Static method Compiles the RegEx and then cashes the result whereas repeatedly creating new instances without the Compiled option mearly uses Interpretation to run the RegEx. Basically what you have is a trade-off between slow initialization and fast execution verses fast initialization and slow execution.

The only reason that the slow initialization is tolerable in a lot of instances is because of the cashing. As a result you need to be using the exact same RegEx over and over again for the Compilation cost to be worth the effort. I believe in the case of the RegEx Editor project what we actually have is lots of different RegEx being used a very small number of times each. This would suggest to me that the Interpreted model (initialization and slow execution) would be a better trade off and as such we should not use the Static method.

Still all this is likely a trivial argument as either way is going to be fast enough that the user of the application will not notice it. The application is likely going to be run on a high powered developer desktop machine with little competition for processor resources and is only likely to be doing one RegEx execution every few seconds rather than performing thousands or millions of transactions a second like a server application would.

 

Editor
Jul 13, 2011 at 5:39 PM

The worse in instance regex is the cache. While it is used as a pool and each time the rules have been changed a new compilation have to be made cache could be easily filled up. Then it should be increased which additionally will slow execution down. This means that in case of instance regex is accepted to be used it will be better to give up instant execution while user is typing... And last, Microsoft itself recommend using static regex.

For me it is clear that static is better than instance for (PC's) resources is hard to manage programatically and sooner or later such attempts cause problems.

Nevertheless I don't mind to restore instance regex usage if you prefer this.