• 高压力下正则表达式的性能瓶颈


    最近在做公司的系统,每秒要接受网络的数据在130条左右,对过长的数据进行截取,使用的方法是:

         /// <summary>
            /// 截断字符串
            /// </summary>
            /// <param name="maxLength">最大长度</param>
            /// <param name="str">原字符串</param>
            /// <returns></returns>
            public static string LeftString(int maxLength, string str)
            {
                if (string.IsNullOrEmpty(str))
                    return "";
                if (maxLength < 0)
                    return str;
    
                string temp = str;
                if (Regex.Replace(temp, "[u4e00-u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= maxLength)
                {
                    return temp;
                }
                for (int i = temp.Length; i >= 0; i--)
                {
                    temp = temp.Substring(0, i);
                    if (Regex.Replace(temp, "[u4e00-u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= maxLength - 3)
                    {
                        return temp + "...";
                    }
                }
                return "...";
            }

    在使用中,系统的cpu一直居高不下,主要集中在w3wp,经常达到70%-80%,服务器经常出现预警。期间百思不得其解,后经过多方排除,替换了这个方法:
            /// <summary>
            /// 截取字符串
            /// </summary>
            /// <param name="str_value"></param>
            /// <param name="str_len"></param>
            /// <returns></returns>
            public static string LeftStringExt(string str, int length)
            {
                int p_num = 0;
                int i;
                string New_Str_value = "";
    
                if (str == "")
                {
                    New_Str_value = "";
                }
                else
                {
                    int Len_Num = str.Length;
                    for (i = 0; i <= Len_Num - 1; i++)
                    {
                        if (i > Len_Num) break;
                        char c = Convert.ToChar(str.Substring(i, 1));
                        if (((int)c > 255) || ((int)c < 0))
                            p_num = p_num + 2;
                        else
                            p_num = p_num + 1;
    
                        if (p_num >= length)
                        {
    
                            New_Str_value = str.Substring(0, i + 1);
                            break;
                        }
                        else
                        {
                            New_Str_value = str;
                        }
                    }
    
                }
                return New_Str_value;
            }
    

      现在w3wp的cpu基本控制在3%-4%之间。

      后来在网上查了一下,发现正则表达式有性能问题,普遍要比普通的方法要慢十几-二十几倍。所以在大数据高并发的情况下要尽量规避使用正则表达式



      

  • 相关阅读:
    linux安装jdk1.8
    Python中import
    Python时间
    Python学习Json
    Hive命令学习
    Hadoop系统中的一些概念
    Hadoop系统命令
    ssh无密码登录设置
    Python学习
    Linux Socket IPC
  • 原文地址:https://www.cnblogs.com/songafeng/p/3989319.html
Copyright © 2020-2023  润新知