简体   繁体   English

快速复制scala中的对象内容

[英]fast copying object content in scala

I have a class with few Int and Double fields. 我有一个Int和Double字段很少的类。 What is the fastes way to copy all data from one object to another? 将所有数据从一个对象复制到另一个对象的方法是什么?

class IntFields {
  private val data : Array[Int] = Array(0,0)

  def first : Int = data(0)
  def first_= (value: Int) = data(0) = value
  def second : Int = data(1)
  def second_= (value : Int) = data(1) = value

  def copyFrom(another : IntFields) =
    Array.copy(another.data,0,data,0,2)
}

This is the way I may suggest. 这是我建议的方式。 But I doubt it is really effective, since I have no clear understanding scala's internals 但我怀疑它是否真的有效,因为我对scala的内部结构没有明确的理解

update1: UPDATE1:

In fact I'm searching for scala's equivalent of c++ memcpy. 实际上我正在搜索scala相当于c ++ memcpy。 I need just take one simple object and copy it contents byte by byte. 我只需要取一个简单的对象并逐字节地复制它。

Array copying is just a hack, I've googled for normal scala supported method and find none. 数组复制只是一个黑客,我已经搜索了正常的scala支持方法,并找不到。

update2: UPDATE2:

I've tried to microbenchmark two holders: simple case class with 12 variables and one backed up with array. 我试过microbenchmark两个持有者:简单的案例类有12个变量,一个用数组备份。 In all benchmarks (simple copying and complex calculations over collection) array-based solution works slower for about 7%. 在所有基准测试中(简单复制和基于集合的复杂计算),基于阵列的解决方案的工作速度较慢,约为7%。

So, I need other means for simulating memcpy. 所以,我需要其他方法来模拟memcpy。

Since both arrays used for Array.copy are arrays of primitive integers (ie it is not the case that one of the holds boxed integers, in which case a while loop with boxing/unboxing would have been used to copy the elements), it is equally effective as the Java System.arraycopy is. 由于用于Array.copy两个数组都是基本整数数组(即不是其中一个保持盒装整数的情况,在这种情况下while使用装箱/拆箱的while循环将用于复制元素),它是与Java System.arraycopy一样有效。 Which is to say - if this were a huge array, you would probably see the difference in performance compared to a while loop in which you copy the elements. 也就是说 - 如果这是一个巨大的数组,你可能会看到与复制元素的while循环相比的性能差异。 Since the array only has 2 elements, it is probably more efficient to just do: 由于数组只有2个元素,因此可能更有效:

def copyFrom(another: IntFields) {
  data(0) = another.data(0)
  data(1) = another.data(1)
}

EDIT: 编辑:

I'd say that the fastest thing is to just copy the fields one-by-one. 我想说最快的就是一个一个地复制字段。 If performance is really important, you should consider using Unsafe.getInt - some report it should be faster than using System.arraycopy for small blocks: https://stackoverflow.com/questions/5574241/interesting-uses-of-sun-misc-unsafe 如果性能非常重要,您应该考虑使用Unsafe.getInt - 有些报告它应该比使用System.arraycopy更快的小块更快: httpsUnsafe.getInt -unsafe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM