我必须使用一种能够以内存有效方式(在 scala 中)对 Ipv4 和 Ipv6 地址进行空洞的类型。他们还应该表现出色。我看到的两个选项是使用 scala BigInt 类型或字节数组。两种情况下的内存/性能命中情况如何?
最佳答案
Java 中的 BigInteger 需要 5 * 4 字节 4 个 int 字段加上 int 数组。 Scala 中的 BigInt 只是 BigInteger 的包装,因此它是相似的。因此使用 Byte
数组肯定会占用更少的空间。
我还可能考虑使用带有伴生对象和隐式扩展的类型别名,以保持类型安全和丰富的 API,而无需额外开销(它仍然与 Array[Byte]
占用相同的空间量。
trait IP
type IPv4 = Array[Byte] with IP //adding "with IP" would make sure compiler won't accept plain Array[Byte] when type IPv4 is needed
type IPv6 = Array[Byte] with IP
object IPv4 { //create similar for IPv6
def apply(ip: String) = {
ip.split("\\.").map(_.toByte).asInstanceOf[IPv4] //you can create IPv4("127.0.0.1")
}
object Implicits {
implicit class RichIPv4(ip: IPv4) {
def show(): String = ip.map(_.toString).mkString(".") //add method to show as string
def verify(): Boolean = ??? //additional methods
}
}
}
import IPV4.Implicits._
def printIP(ip: IPv4) = println(ip.show) //Will only accept arrays created by IPv4.apply
printIP(IPv4("127.0.0.1")) //ok
printIP(Array[Byte](127,0,0,1)) //won't compile
或者,您应该看看很棒的库 scala-newtype ,它做了类似的事情,但没有额外的样板。
关于java - scala 中 BigInt 与 Byte 数组的内存和性能比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55413287/