![](/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.