c# 中字符串搜索 indexof 与 正则表达式效率比较

时间:2022-02-01 10:39:53
        public void 性能测试()
{
string res = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<xxxMsg xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n <Message>10</Message>\r\n <Time>2014-04-30T15:26:15.3256946+08:00</Time>\r\n <SyncPointTagName>ddddd</SyncPointTagName>\r\n <TerminalCode>50001334</TerminalCode>\r\n</xxxMsg>";

//100万次计算
var arr = System.Linq.Enumerable.Range(1, 1000000);

//方法1
Action act = () => { foreach (var k in arr) { forFun(res); } };

//方法2
Action act2 = () => { foreach (var k in arr) { forRegx(res); } };

//fro 用时7860
System.Diagnostics.Debug.WriteLine("fro 用时" + Stopwatch(act));
//regx 用时1056
System.Diagnostics.Debug.WriteLine("regx 用时" + Stopwatch(act2));

}


/// <summary>
/// 用for查找
/// </summary>
/// <param name="res"></param>
protected void forFun(string res)
{
//这东西写到外部,效率应该会高一点点
string msg = string.Empty;
string tag = "<Message>";
int startindex =res.IndexOf(tag) + tag.Length;
int endindex = -1;
for (int k = startindex; k < res.Length; k++)
{
char curchar = res[k];
if (curchar >= 48 && curchar <= 57)
{
endindex = k;//这里还可以用msg+=curchar ;
                }                else                {                    break;                }            }            msg = res.Substring(startindex, endindex - startindex);        }        /// <summary>        /// 正则查找        /// </summary>        /// <param name="res"></param>        protected void forRegx(string res)        {            //这东西写到外部,效率应该会高一点点            string msg = string.Empty;            string tag = "<Message>";            msg = System.Text.RegularExpressions.Regex.Match(res, tag + "\\d{1,}").Value;        }        /// <summary>        /// 测试运行时间        /// </summary>        /// <param name="method">需要执行的方法</param>        /// <param name="summary">对方法的说明</param>        /// <returns>返回,这个方法执行用了多少毫秒</returns>        public static long Stopwatch(Action method)        {            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();            watch.Restart();            //运行方法            method.Invoke();            watch.Stop();            return watch.ElapsedMilliseconds;        }        /// <summary>        /// 测试运行时间        /// </summary>        /// <param name="method">需要执行的方法</param>        /// <param name="obj">参数对像</param>        /// <returns>返回,这个方法执行用了多少毫秒</returns>        public static long Stopwatch<T>(Action<T> method, T obj)        {            return Stopwatch(new Action(() =>                                            {                                                method.Invoke(obj);                                            }));        }
可以看到,,,,使用正则表达式的结果需要10秒左右,而使用indexof 的搜索只需要7秒多.