首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala中典型种的性能

问Scala中典型种的性能
EN

Stack Overflow用户
提问于 2016-04-07 13:15:30
回答 1查看 262关注 0票数 3

我试图分析Scala中使用类型类的性能成本,因为我注意到当它们被广泛使用时,性能往往会下降。例如,让我们以一个ByteCodec类型为例:

代码语言:javascript
复制
trait ByteCodec[T] {
  def put(index: Int, byteBuffer: ByteBuffer, t: T): Unit
  def get(index: Int, byteBuffer: ByteBuffer): T
}

然后,让我们创建一个Long实例:

代码语言:javascript
复制
object ByteCodec {
  def apply[T](implicit bc: ByteCodec[T]): ByteCodec[T] = bc

  implicit val longBC = new ByteCodec[Long] {
    @inline override def put(index: Int, byteBuffer: ByteBuffer, long: Long): Unit = {
      val _ = byteBuffer.putLong(index, long)
    }

    @inline override def get(index: Int, byteBuffer: ByteBuffer): Long =
      byteBuffer.getLong(index)
  }
}

如果我运行1亿获取和投入,这需要1200 If的类型测试和~800 If否则。头顶在哪里,我能把它处理掉吗?

主要代码:

代码语言:javascript
复制
object Main extends App {
  val cycles = 100000000
  val byteBuffer = ByteBuffer.allocate(java.lang.Long.BYTES)
  var start = System.currentTimeMillis()
  var currCycle = cycles
  while (currCycle > 0) {
    byteBuffer.putLong(0, 10L)
    val k = byteBuffer.getLong(0)
    currCycle -= 1
  }
  var end = System.currentTimeMillis()
  println(s"time elapsed byteBuffer ${ end - start }")

  val codec = ByteCodec[Long]
  start = System.currentTimeMillis()
  currCycle = cycles
  while (currCycle > 0) {
    codec.put(0, byteBuffer, 10L)
    val k = codec.get(0, byteBuffer)
    currCycle -= 1
  }
  end = System.currentTimeMillis()
  println(s"time elapsed ByteCodec ${ end - start }")
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-07 13:30:50

亚历克西在评论中已经提到了你的测试不准确的原因之一。

除此之外,类型比较慢的主要原因与方法本身无关:是Long的boxing/unboxing使其变慢。可以使用 annotation为值类专门化类型。

代码语言:javascript
复制
trait ByteCodec[@specialized(Long) T]

如果您查看来自ByteBuffer的签名,就会使用值类型,而不涉及装箱/取消装箱:

代码语言:javascript
复制
 public abstract ByteBuffer putLong(int index, long value);
 public abstract long getLong(int index);
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36477373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档