简体   繁体   中英

fast copying object content in scala

I have a class with few Int and Double fields. 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

update1:

In fact I'm searching for scala's equivalent of 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.

update2:

I've tried to microbenchmark two holders: simple case class with 12 variables and one backed up with array. In all benchmarks (simple copying and complex calculations over collection) array-based solution works slower for about 7%.

So, I need other means for simulating 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. 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. Since the array only has 2 elements, it is probably more efficient to just do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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