总结:频繁调用的方法中,避免创建Regex对象
刚在项目中发现个使用Regex 的问题,在高并发的情况下函数被频繁调用,不恰当的使用Regex,导致cpu 接近90%。
案例:
namespace TB.General
{
public class Email
{
public static ArrayList GetEmail(string content)
{
string pattern = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
ArrayList arrayList = new ArrayList();
Regex regex = new Regex(pattern, RegexOptions.Compiled);
MatchCollection matchCollecti
.Compiled参数,但是用法不对,反而导致性能比不使用RegexOptions.Compiled参数还要下降N倍,在高并发的情况下给程序带来了灾难。
正确用法:
namespace TB.General
{
public class Email
{
private static Regex regex = new Regex("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", RegexOptions.Compiled);
public static ArrayList GetEmail(string content)
{
ArrayList arrayList = new ArrayList();
MatchCollection matchCollection = regex.Matches(content);
if (matchCollection.Count != 0)
{
for (int i = 0; i < matchCollection.Count; i++)
{
string value = matchCollection[i].Groups[0].Value;
if (!arrayList.Contains(value))
{
arrayList.Add(value);
}
}
}
return arrayList;
}
}
}