[英]Memory and Perf comparison of BigInt vs Byte array in scala
I have to use a type that can hole Ipv4 and Ipv6 addresses in memory efficient manner (in scala). 我必须使用一种可以以内存有效方式(在Scala中)对Ipv4和Ipv6地址进行穿孔的类型。 As well as they should be performant.
以及他们应该表现出色。 The two options I see are, using the scala BigInt type or a byte array.
我看到的两个选项是使用scala BigInt类型或字节数组。 What the memory/perf hit in both cases?
在这两种情况下,内存/性能都有哪些变化?
BigInteger in Java takes 5 * 4 bytes
for 4 int
fields plus int
array. Java中的BigInteger需要
5 * 4 bytes
int
字段加上int
数组占用5 * 4 bytes
。 BigInt from Scala is just wrapper over BigInteger so it would be similar. Scala的BigInt只是BigInteger的包装,因此类似。 So using
Byte
array would definitely take less place. 因此,使用
Byte
数组肯定会减少位置。
I might also consider using type aliases with companion object and implicit extensions to keep type safety and rich API without additional overhead (it will still the same amount of space as Array[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
Alternatively, you should take a look at the great library scala-newtype , which does similar things but without additional boilerplate. 另外,您应该看看很棒的库scala-newtype ,它执行类似的操作,但没有其他样板文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.