次のコードは、私のプログラムで最もホットなスポットのようです。
JAVA_OPTS=-Xprof 出力:
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
Slice、sameElements、さらには foreach 呼び出しもここから最も使用されているようです。メソッドを最適化する方法について誰かがアドバイスをくれますかcontains()
? たぶん、整数に変換せずにバイト分析を可能にするいくつかのテクニックはありますか? または、スライスなしの堅実な全配列アプローチですか?
関数 SubNet.contains() は、サブネットに対して IP アドレスを照合します。
object SubNet {
def toInts(bytes: Seq[Byte]): Seq[Int] = bytes.map(_.toInt & 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 && 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) >> (8-bits) ^ subnet(bytes) >> (8-bits)) & 0xFF) == 0
}
}
}
}
}
この最適化によってスループットが大幅に向上するわけではないことは理解していますが、この単純な関数内で多くの時間を費やしているのは間違っていると感じています。
このコードは IPv6 (16 バイト) 互換である必要があり、IPv4 のケースを個別に処理するという考えは好きではありません。