title: Optimal IP subnet matching
body: <p>The following code appears to be the hottest spot in my program.</p>
  
  <p>JAVA_OPTS=-Xprof output:</p>
  
  <pre><code>     Compiled + native   Method
    5.7%   173  +     0    scala.collection.IndexedSeqOptimized$class.slice
    5.1%   156  +     0    scala.collection.IndexedSeqOptimized$class.foreach
    2.9%    87  +     0    java.util.regex.Pattern$BmpCharProperty.match
    2.5%    76  +     0    scala.collection.IndexedSeqOptimized$class.sameElements
    2.4%    73  +     0    trafacct.SubNet.contains
  </code></pre>
  
  <p>Slice, sameElements and even foreach calls seem to be most used from here too. Can someone give an advice or two on how to optimize <code>contains()</code> method? Maybe some techniques allowing Bytes analysis without converting them to integers? Or solid whole-sequence approach without slice?</p>
  
  <p>Function SubNet.contains() matches an IP address against subnet.</p>
  
  <pre><code>object SubNet {
      def toInts(bytes: Seq[Byte]): Seq[Int] = bytes.map(_.toInt &amp; 0xFF)
  }
  
  case class SubNet(ip:InetAddress,  maskLength:Int) extends HostCategory {
      import SubNet.toInts
      private val bytes: Int = maskLength / 8
      private val subnet = toInts(ip.getAddress)
      private val bits = bytes * 8 - maskLength
      def contains(host: Host) = {
          if (host.ip == null &amp;&amp; ip == null) {
              true
          } else if (this.ip == null) {
              false
          } else {
              val address = toInts(host.ip.getAddress)
              if (address.length != subnet.length) {
                  false
              } else {
                  if (address.slice(0, bytes) != subnet.slice(0, bytes)) {
                      false
                  } else {
                      ((address(bytes) &gt;&gt; (8-bits) ^ subnet(bytes) &gt;&gt; (8-bits)) &amp; 0xFF) == 0
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>I understand, that this optimization won't give me much better throughput, I just feel that I'm doing something wrong spending so much time inside this simple function.</p>
  
  <p>This code should be IPv6  (16 bytes) compatible, and I don't like the idea of handling IPv4 case separately.</p>