Scala中BigInt与Byte数组的内存和性能比较

时间:2019-03-29 08:31:46

标签: java scala ipv6 biginteger inetaddress

我必须使用一种可以以内存有效方式(在Scala中)对Ipv4和Ipv6地址进行穿孔的类型。以及他们应该表现出色。我看到的两个选项是使用scala BigInt类型或字节数组。两种情况下的记忆/性能如何?

1 个答案:

答案 0 :(得分:0)

Java中的BigInteger需要5 * 4 bytes来容纳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,该库执行类似的操作,但没有其他样板。