title: Why is looping through an array several times faster the second time around in Go?
body: <p>This is a simple script that just filters out certain characters.</p>
  <p>I was comparing the regex version to the array version and found enormous speed improvements, but I noticed that doing the same array statement again increases the speed several-fold. I'm re-initializing all the variables - I think - so I'm trying to understand why this is happening.</p>
  <pre><code>func checkFormat(s string) (bool, string) {
  
      const allowedCharacters = &quot;abcdefghijkklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-&quot;
      var reg, _ = regexp.Compile(&quot;[^A-Za-z0-9-]+&quot;)
  
      start := time.Now()
      filteredRegex := reg.ReplaceAllString(s, &quot;&quot;)
      end := time.Since(start)
      fmt.Println(&quot;REGEX: &quot;, end)
  
      start = time.Now()
      equalsArray := make([]rune, len(s))
      removed := 0
      for i, r := range s {
          if (r &gt;= 97 &amp;&amp; r &lt;= 122) || (r &gt;= 65 &amp;&amp; r &lt;= 90) || (r &gt;= 48 &amp;&amp; r &lt;= 57) || r == 45 {
              equalsArray[i-removed] = r
          } else {
              removed++
          }
      }
      end = time.Since(start)
      fmt.Println(&quot;FIRST: &quot;, end)
  
      start = time.Now()
      equalsArrayx := make([]rune, len(s))
      removedx := 0
      for i, r := range s {
          if (r &gt;= 97 &amp;&amp; r &lt;= 122) || (r &gt;= 65 &amp;&amp; r &lt;= 90) || (r &gt;= 48 &amp;&amp; r &lt;= 57) || r == 45 {
              equalsArrayx[i-removedx] = r
          } else {
              removedx++
          }
      }
      end = time.Since(start)
      fmt.Println(&quot;SECOND: &quot;, end)
  
      if filteredRegex == s {
          return true, filteredRegex
      } else {
          return false, filteredRegex
      }
  }
  </code></pre>
  <p>Output:</p>
  <pre><code>REGEX:  23.917µs
  FIRST:  3.208µs
  SECOND:  708ns
  </code></pre>