none
Static methods x Instance methods RRS feed

  • Question

  • Hi,I have a question that poped when I was reading the documentation for Regex class :

    "The two static IsMatch methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method IsMatch. The static methods are provided to allow an isolated, single use of a regular expression without explicitly creating a Regex object."


    Before reading this I had a code that tested an array of strings containing regular expressions against a huge text file using the one of the static version of IsMatch above and it took arround 50 seconds on my computer to execute the code. When I changed to an array of Regex objects the code took 14 seconds to execute.


    After this experience I got kinda afraid of static methods because I tought the code for them should be allocated only once in the compilation of the program as oposed to this exemple where for every line of the text file it created an instance of the Regex class for every string I had in the array(the numer of objects created before was [Numeroflines*Lenghtofthearray] and [Lenghtofthearray] in the second case.


    So my question is :


    How exactly does static methods works? If I have a static method inside a loop does it implicitly creates an instance of the class containing it before executing ? If so how do I stop this?



    Monday, April 21, 2008 2:08 PM

Answers

  • Static methods in .NET is called faster then instance ones.

    In Regex class static method IsMatch is slower, because internally this method creates instance of Regex class and calls appropriate instance method.

    Monday, April 21, 2008 2:45 PM

All replies

  • Static methods in .NET is called faster then instance ones.

    In Regex class static method IsMatch is slower, because internally this method creates instance of Regex class and calls appropriate instance method.

    Monday, April 21, 2008 2:45 PM
  • Specifically, the regex construction is not trivial (the regex expression must be parsed).  Creating a regex for each match is therefore costly.

     

    By the way, you can get even better performance if you compile the regex (using Regex.CompileToAssembly).  This will be significantly faster if you're matching the same expression against many different inputs.  This compiled assembly can also be cached and loaded directly.

     

    Monday, April 21, 2008 5:28 PM