title: Should I cache a comparer in a static field?
body: <p>I have added the following property to my <code>ApplicationUser</code> class, which is supposed to return current user on top of other results.</p>
  
  <pre><code>public static IComparer&lt;string&gt; IdComparer
  {
    get
    {
      return Comparer&lt;string&gt;.Create((x, y) =&gt;
          {
            var curUser = HttpContext.Current.User;
            if (curUser != null)
            {
              var curId = curUser.Identity.GetUserId();
              if (x == curId)
                return -1;
              else if (y == curId)
                return 1;
            }
            return string.Compare(x, y);
          });
    }
  }
  </code></pre>
  
  <p>Anyway, does generating a comparer cost more than storing it? Should I add a static field and return a singleton for this property?</p>
  
  <p>I'm thinking about returning the same comparer:</p>
  
  <pre><code>private static object sync = new object();
  private static IComparer&lt;string&gt; _IdComparer;
  public static IComparer&lt;string&gt; IdComparer
  {
    get
    {
      if (_IdComparer == null)
        lock (sync)
          if (_IdComparer == null)
            _IdComparer = Comparer&lt;string&gt;.Create((x, y) =&gt;
                {
                  var curUser = HttpContext.Current.User;
                  if (curUser != null)
                  {
                    var curId = curUser.Identity.GetUserId();
                    if (x == curId)
                      return -1;
                    else if (y == curId)
                      return 1;
                  }
                  return string.Compare(x, y);
                });
      return _IdComparer;
    }
  }
  </code></pre>
  
  <p>Is this safe? Any corrections or enhancements?</p>