![](/img/trans.png)
[英]BigInteger to byte array, with size of bigint at the beginning of array
[英]Memory and Perf comparison of BigInt vs Byte array in scala
我必须使用一种可以以内存有效方式(在Scala中)对Ipv4和Ipv6地址进行穿孔的类型。 以及他们应该表现出色。 我看到的两个选项是使用scala BigInt类型或字节数组。 在这两种情况下,内存/性能都有哪些变化?
Java中的BigInteger需要5 * 4 bytes
int
字段加上int
数组占用5 * 4 bytes
。 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 ,它执行类似的操作,但没有其他样板文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.