Performance difference between declaring Regex inside or outside of often-called method. I am curious as to what the performance/functional differences are between:

private bool OftenCalledMethod(string s)
{
    Regex reg = new Regex(@"^matchme$", RegexOptions.IgnoreCase);
    return (reg.IsMatch(s));
}


Versus:

readonly Regex reg = new Regex(@"^matchme$", RegexOptions.IgnoreCase);
private bool OftenCalledMethod(string s)
{
    return (reg.IsMatch(s));
}


Does the compiler optimize the former in such a way that it doesn't matter? Or is the object reg being allocated repeatedly and unnecessarily?
I would go with the former unless you profile your code and it tells you that the constructor for Regex is using a significant amount of time.

Creating the Regex inside your method makes the clear statement that this given Regex is being used by only this method.  The compiler doesn't care, but someone maintaining your code in the future might care.

Running a profiler is necessary for really optimizing your code.  There are some things that are always likely to be bad (O(n^3) algorithms for instance), but I've learned by experience that I can't tell just by looking where the time is being wasted in my code.  Profile it and see what you learn.

If your profiling results tell you that the constructor of Regex is using too much time, then definitely move it outside the method.  If you do that though, you should add comments explaining why.  (Keep thinking about the poor person maintaining your code in the future, it just might be you.)