title: Performance impact due to store.Open and store.Certificates.Find methods in X509Store
body: <pre><code>private static X509Certificate2 FindCertificate(string certificateSubject)
  {
      const StoreName StoreName = StoreName.My;
      const StoreLocation StoreLocation = StoreLocation.LocalMachine;
  
      var store = new X509Store(StoreName, StoreLocation); 
      try
      {
          store.Open(OpenFlags.ReadOnly);
  
          // Find with the FindBySubjectName does fetch all the certs partially matching the subject name.
          // Hence, further filter for the certs that match the exact subject name.
          List&lt;X509Certificate2&gt; clientCertificates =
              store.Certificates.Find(X509FindType.FindBySubjectName, certificateSubject, validOnly: true)
                  .Cast&lt;X509Certificate2&gt;()
                  .Where(c =&gt; string.Equals(
                      c.Subject.Split(',').First().Trim(),
                      string.Concat("CN=", certificateSubject).Trim(),
                      StringComparison.OrdinalIgnoreCase)).ToList();
  
          if (!clientCertificates.Any())
          {
              throw new InvalidDataException(
                  string.Format(CultureInfo.InvariantCulture, "Certificate {0} not found in the store {1}.", certificateSubject, StoreLocation.LocalMachine));
          }
  
          X509Certificate2 result = null;
          foreach (X509Certificate2 cert in clientCertificates)
          {
              DateTime now = DateTime.Now;
              DateTime effectiveDate = DateTime.Parse(cert.GetEffectiveDateString(), CultureInfo.CurrentCulture);
              DateTime expirationDate = DateTime.Parse(cert.GetExpirationDateString(), CultureInfo.CurrentCulture);
              if (effectiveDate &lt;= now &amp;&amp; expirationDate.Subtract(now) &gt;= TimeSpan.FromDays(1))
              {
                  result = cert;
                  break;
              }
          }
  
          return result;
      }
      finally
      {
          store.Close();
      }
  }
  </code></pre>
  
  <p>I have this code in my library and everytime a new request is created it calls this method. So basically is the requests per second is 1000 then it will be called 1000 times. When i was using the PerfView tool i noticed that 35% of the CPU is used by this method. Biggest culprit being store.Open and store.Certificates.Find method.</p>
  
  <p>Anybody else has found out similar issues in their code. Also if you can share what did you do to resolve the performance impact due to this.</p>