When not to use RegexOptions.Compiled

前端 未结 4 1106
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 06:10

I understand the advantage of using RegexOptions.Compiled - it improves upon the execution time of app by having the regular expression in compiled form instead of interpre

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 06:11

    Compilation generally only improves performance if you are saving the Regex object that you create. Since you are not, in your example, saving the Regex, you should not compile it.

    You might want to restructure the code this way (note I re-wrote the regex to what I think you want. Having the start-of-line carat in a repeating group doesn't make a whole lot of sense, and I assume a name prefix ends with a dash):

        private static readonly Regex CompiledRegex = new Regex("^[a-zA-Z]+-", RegexOptions.Compiled);
        private static string GetNameCompiled(string objString)
        {
            return CompiledRegex.Replace(objString, "");
        }
    

    I wrote some test code for this also:

        public static void TestSpeed()
        {
            var testData = "fooooo-bar";
            var timer = new Stopwatch();
    
            timer.Start();
            for (var i = 0; i < 10000; i++)
                Assert.AreEqual("bar", GetNameCompiled(testData));
            timer.Stop();
            Console.WriteLine("Compiled took " + timer.ElapsedMilliseconds + "ms");
            timer.Reset();
    
            timer.Start();
            for (var i = 0; i < 10000; i++)
                Assert.AreEqual("bar", GetName(testData));
            timer.Stop();
            Console.WriteLine("Uncompiled took " + timer.ElapsedMilliseconds + "ms");
            timer.Reset();
    
        }
    
        private static readonly Regex CompiledRegex = new Regex("^[a-zA-Z]+-", RegexOptions.Compiled);
        private static string GetNameCompiled(string objString)
        {
            return CompiledRegex.Replace(objString, "");
        }
    
        private static string GetName(string objString)
        {
            return Regex.Replace(objString, "^[a-zA-Z]+-", "");
        }
    

    On my machine, I get:

    Compiled took 21ms

    Uncompiled took 37ms

提交回复
热议问题