title: Is it useful to check if a Java collection is empty before beginning iteration?
body: <p>In the two styles below, an <code>Iterator</code> object is allocated.  Is it useful to check if the collection is empty before iterating?  I don't know if this qualifies as "premature optimization".  Hopefully, someone with deep knowledge of JVM garbage collectors can provide insight.</p>
  
  <p>Also, I don't know how the Java compiler handles for-each loops.  I assume style <strong>B</strong> is converted to style <strong>A</strong> automatically.  But... maybe an empty check is included.</p>
  
  <p><strong>Loop Style A</strong></p>
  
  <pre><code>Collection&lt;String&gt; collection = ...
  Iterator&lt;String&gt; iter = collection.iterator();
  while (iter.hasNext()) {
      String value = iter.next();
      // do stuff
      // maybe call iter.remove()
  }
  </code></pre>
  
  <p><strong>Loop Style B</strong></p>
  
  <pre><code>Collection&lt;String&gt; collection = ...
  for (String value : collection) {
      // do stuff
  }
  </code></pre>
  
  <p><strong>Loop Style A (Modified)</strong></p>
  
  <pre><code>Collection&lt;String&gt; collection = ...
  if (!collection.isEmpty()) {
      Iterator&lt;String&gt; iter = collection.iterator();
      while (iter.hasNext()) {
          String value = iter.next();
          // do stuff
          // maybe call iter.remove()
      }
  }
  </code></pre>
  
  <p><strong>Loop Style B (Modified)</strong></p>
  
  <pre><code>Collection&lt;String&gt; collection = ...
  if (!collection.isEmpty()) {
      for (String value : collection) {
          // do stuff
      }
  }
  </code></pre>