title: Does equality test order affect performance in Java?
body: <p>I commonly find myself writing code like this:</p>
  
  <pre><code>private List&lt;Foo&gt; fooList = new ArrayList&lt;Foo&gt;();
  
  public Foo findFoo(FooAttr attr) {
      for(Foo foo : fooList) {
          if (foo.getAttr().equals(attr)) {
              return foo;
          }
      }
  }
  </code></pre>
  
  <p>However, assuming I properly guard against null input, I could also express the loop like this:</p>
  
  <pre><code>for(Foo foo : fooList) {
      if (attr.equals(foo.getAttr()) {
          return foo;
      }
  }
  </code></pre>
  
  <p>I'm wondering if one of the above forms has a performance advantage over the other.  I'm well aware of the dangers of premature optimization, but in this case, I think the code is equally legible either way, so I'm looking for a reason to prefer one form over another, so I can build my coding habits to favor that form.  I think given a large enough list, even a small performance advantage could amount to a significant amount of time.</p>
  
  <p>In particular, I'm wondering if the second form might be more performant because the <code>equals()</code> method is called repeatedly on the same object, instead of different objects?  Maybe branch prediction is a factor?</p>