Which is faster: using regular expressions or native code?

2020年2月23日 3410点热度 0人点赞 4条评论
内容目录

Example:
Determining whether a string consists of alphanumeric characters and underscores:

using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace ConsoleApp6
{
    class Program
    {
        static Regex regex = new Regex(@"^[A-Za-z0-9]+$");
        static void Main(string[] args)
        {
            string[] a = new string[] {
                "Absdbkbs",
                "asdf4642`",
                "fsdg4654fs4",
                "r23fwegf34",
                "e23rwef,",
                "fewfsg35453453",
                "545345415",
                "dalsjfiose2",
                "dasfwetr23`",
                "dsaf5454-"};
            System.Threading.Thread.Sleep(5000);
            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i = 0; i < 1_0_0000; i++)
            {
                for (int k = 0; k < a.Length; k++)
                {
                    var tmp = IsNumAndEnCh(a[k]);
                }
            }
            watch.Stop();
            Console.WriteLine("Execution of 10 0000 * 10 regex verification: " + watch.ElapsedMilliseconds);

            watch.Restart();

            for (int i = 0; i < 1_0_0000; i++)
            {
                for (int k = 0; k < a.Length; k++)
                {
                    var tmp = IsHas(a[k]);
                }
            }
            watch.Stop();
            Console.WriteLine("Execution of 10 0000 * 10 C# code verification: " + watch.ElapsedMilliseconds);
            Console.ReadKey();
        }
        /// <summary>
        /// Determine if the input string contains only numbers and English letters
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsNumAndEnCh(string input)
        {
            return regex.IsMatch(input);
        }
        public static bool IsHas(string input)
        {
            ReadOnlySpan<char> span = input.AsSpan();
            for (int i = 0; i < span.Length; i++)
            {
                if (!char.IsLetterOrDigit(span[i]))
                    return false;
            }
            return true;
        }
    }
}

The output results are:

Execution of 10 0000 * 10 regex verification: 986
Execution of 10 0000 * 10 C# code verification: 237

The raw code is indeed faster than the regular expression.

痴者工良

高级程序员劝退师

文章评论