首页 > 解决方案 > C# 性能,加速类中的字符串数组

问题描述

我需要更多的性能,这就是我目前所拥有的。

public static class ValidateConditions
{

     public static bool CheckWildCards(string hcdpPlnCvgCD, string HcdpPmtFctrCd, string hccCpmtFctrCd, IBizClaimWorkflowContext workspaceContext, string conditionType)
     {
         var patterns = new string[3];
         
         if(condition)
         {
            patterns = new string[]{
                 hcdpPlnCvgCD,
                "DEF",
                "HIJ"
            };
         }
         else
         {
            patterns = new string[]{
                 hcdpPlnCvgCD,
                "yyy",
                "zzz"
            };
         }
         
          var matchResult = dataMart.SponsorPackage.Where(s => Regex.IsMatch(s.ExternalPolicy, pattern)).FirstOrDefault();

     }

}

我听说这可能是一个性能问题,因为“这些数组应该声明为私有静态,因为我们只在类初始化时创建每个数组一次,而不是每次调用方法时创建一个新数组。因为它是每天调用一百万次。

所以我对如何实现这一点有点困惑。

我正在考虑在课堂上这样做, private static string[] patterns { get; set; } 但我最终还是不得不做 `new string[]{...} 那么我怎样才能真正正确地做到这一点?

更新:修复代码。

标签: c#arraysperformance

解决方案


只初始化一次变量。

public static class ValidateConditions
{
    private static string[] Patterns1 = new string[]{
        "ABC",
        "DEF",
        "HIJ"
    };
    private static string[] Patterns2 = new string[]{
        "xxx",
        "yyy",
        "zzz"
    };

    public static bool CheckWildCards(MyClass data, bool condition)
    {
        var patterns = condition ? Patterns1 : Patterns2; 
         
        var matchResult = data.SponsorPackage.Where(s => MyMethod(s.ExternalPolicy, pattern)).FirstOrDefault();
        //etc....
    }
}

推荐阅读