判断访问链接是否是静态资源

背景

分别使用 EndsWith 和 Regex 判断 url 请求是否是静态资源

  static void Main(string[] args)
  {
      int num = 1000000;

      string[] suffix = { ".js", ".css", ".jpg", ".png", ".gif", ".JS", ".CSS", ".JPG", ".PNG", ".GIF", };


      Stopwatch stopwatch = Stopwatch.StartNew();
      for (int i = 0; i < num; i++)
      {

          IsStaticResource_EndsWith(i + suffix[i % 10]);
      }

      stopwatch.Stop();

      Console.WriteLine($"IsStaticResource_EndsWith 执行 {num} 次,耗时 {stopwatch.ElapsedMilliseconds} ms");

      stopwatch.Restart();
      for (int i = 0; i < num; i++)
      {

          IsStaticResource_Regex(i + suffix[i % 10]);
      }

      stopwatch.Stop();

      Console.WriteLine($"IsStaticResource_Regex 执行 {num} 次,耗时 {stopwatch.ElapsedMilliseconds} ms");
  }


  /// <summary>
  /// 判断是否是静态资源
  /// </summary>
  /// <remarks>js,css,jpg,png,gif</remarks>
  /// <param name="request"></param>
  /// <returns></returns>
  public static bool IsStaticResource_EndsWith(string path)
  {
      if (string.IsNullOrWhiteSpace(path))
      {
          return false; 
      }
      if (path.EndsWith(".js", StringComparison.CurrentCultureIgnoreCase)
           || path.EndsWith(".css", StringComparison.CurrentCultureIgnoreCase)
           || path.EndsWith(".jpg", StringComparison.CurrentCultureIgnoreCase)
           || path.EndsWith(".png", StringComparison.CurrentCultureIgnoreCase)
           || path.EndsWith(".gif", StringComparison.CurrentCultureIgnoreCase))
      {
          return true;
      }

      return false;
  }



  /// <summary>
  /// 匹配静态资源
  /// </summary>
  private static readonly Regex resourceRegex = new Regex("(.*.js|.*.css|.*.jpg|.*.jpeg|.*.png|.*.gif)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

  /// <summary>
  /// 判断是否是静态资源
  /// </summary>
  /// <remarks>.*.js|.*.css|.*.jpg|.*.jpeg|.*.png|.*.gif</remarks>
  /// <param name="request"></param>
  /// <returns></returns>
  public static bool IsStaticResource_Regex(string path)
  {
      if (string.IsNullOrWhiteSpace(path))
      {
          return false; 
      }
      return resourceRegex.IsMatch(path);
  }

测试结果

  • 10 万次 EndsWith 比 Regex 性能高

  • 100 万次 Regex 比 EndsWith 性能高

  • 1000 万次 Regex 比 EndsWith 性能高

posted on 2023-02-09 09:48  爱上键盘的蜗牛  阅读(127)  评论(0编辑  收藏  举报

导航