Regex vs Tryparse what is the best in performance

后端 未结 4 1249
日久生厌
日久生厌 2021-01-17 16:25

In my ASP.net project I need to validate some basic data types for user inputs. The data types are like numeric, decimal, datetime etc.

What is the best approach t

4条回答
  •  一向
    一向 (楼主)
    2021-01-17 16:58

    As other would say, the best way to answer that is to measure it ;)

        static void Main(string[] args)
        {
    
            List meansFailedTryParse = new List();
            List meansFailedRegEx = new List();
            List meansSuccessTryParse = new List();
            List meansSuccessRegEx = new List();
    
    
            for (int i = 0; i < 1000; i++)
            {
    
    
                string input = "123abc";
    
                int res;
                bool res2;
                var sw = Stopwatch.StartNew();
                res2 = Int32.TryParse(input, out res);
                sw.Stop();
                meansFailedTryParse.Add(sw.Elapsed.TotalMilliseconds);
                //Console.WriteLine("Result of " + res2 + " try parse :" + sw.Elapsed.TotalMilliseconds);
    
                sw = Stopwatch.StartNew();
                res2 = Regex.IsMatch(input, @"^[0-9]*$");
                sw.Stop();
                meansFailedRegEx.Add(sw.Elapsed.TotalMilliseconds);
                //Console.WriteLine("Result of " + res2 + "  Regex.IsMatch :" + sw.Elapsed.TotalMilliseconds);
    
                input = "123";
                sw = Stopwatch.StartNew();
                res2 = Int32.TryParse(input, out res);
                sw.Stop();
                meansSuccessTryParse.Add(sw.Elapsed.TotalMilliseconds);
                //Console.WriteLine("Result of " + res2 + " try parse :" + sw.Elapsed.TotalMilliseconds);
    
    
                sw = Stopwatch.StartNew();
                res2 = Regex.IsMatch(input, @"^[0-9]*$");
                sw.Stop();
                meansSuccessRegEx.Add(sw.Elapsed.TotalMilliseconds);
                //Console.WriteLine("Result of " + res2 + "  Regex.IsMatch :" + sw.Elapsed.TotalMilliseconds);
            }
    
            Console.WriteLine("Failed TryParse mean execution time     " + meansFailedTryParse.Average());
            Console.WriteLine("Failed Regex mean execution time        " + meansFailedRegEx.Average());
    
            Console.WriteLine("successful TryParse mean execution time " + meansSuccessTryParse.Average());
            Console.WriteLine("successful Regex mean execution time    " + meansSuccessRegEx.Average());
        }
    }
    

提交回复
热议问题