3

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.

ayvango
  • 5,867
  • 3
  • 34
  • 73

1 Answers1

1

Since both arrays used for Array.copy are arrays of primitive integers (i.e. 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

Community
  • 1
  • 1
axel22
  • 32,045
  • 9
  • 125
  • 137
  • it supposed to have about 12 fields. – ayvango Sep 29 '12 at 17:42
  • I'd still say it would be more efficient to copy the directly, however, I'd write a microbenchmark if this is performance-critical, to confirm this. See http://docs.scala-lang.org/overviews/parallel-collections/performance.html on writing microbenchmarks. – axel22 Sep 29 '12 at 17:46