使用正则表达式和原生代码哪个比较快

内容纲要

示例:
判断字符串是否由字母数字下划线组成:

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("执行10 0000 * 10 正则表达式验证:" + 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("执行10 0000 * 10 C#代码验证:" + watch.ElapsedMilliseconds);
            Console.ReadKey();
        }
        /// <summary>
        /// 判断输入的字符串是否只包含数字和英文字母
        /// </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;
        }
    }
}

输出结果是

执行10 0000 * 10 正则表达式验证:986
执行10 0000 * 10 C#代码验证:237

原生代码确实比正则表达式快。

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注