kfmfe04
kfmfe04

Reputation: 15327

When does Scala actually copy objects?

Background

I have a chunk of code that looks like this:

val big_obj = new BigObj
big_obj.recs[5].foo()
... // other code
big_obj.recs[7].bar()

Problem

I want to do something like this

val big_obj = new BigObj
alias ref = big_obj.recs  // looking for something like an alias
ref[5].foo()
... // other code
ref[7].bar()

because I am afraid of making copies of big objects (coming from C++). But then I realised that Scala is probably smart and if I simply do this:

val big_obj = new BigObj
val ref = big_obj.recs  // no copies made?

the compiler is probably smart enough to not copy anyways, since it's all read-only.

Question

This got me wondering about Scala's memory model.

Under what situations will copies be made/not made?

I am looking for a simple answer or rule-of-thumb which I can keep in my mind when I deal with really_big_objects, whenever I make assignments, including passing arguments.

Upvotes: 1

Views: 622

Answers (1)

dhg
dhg

Reputation: 52681

Just like Java (and python and probably a lot of other languages), copies are never made of objects. When you assign an object or pass it as an argument, it only copies the reference to the object; the actual object just sits in memory and has an extra thing pointing to it. The only things that would get copied are primitives (integers, doubles, etc).

As you pointed out, this is obviously good for immutable objects, but it's true of all objects, even mutable ones:

scala> val a = collection.mutable.Map(1 -> 2)
a: scala.collection.mutable.Map[Int,Int] = Map(1 -> 2)

scala> val b = a
b: scala.collection.mutable.Map[Int,Int] = Map(1 -> 2)

scala> b += (2 -> 4)
res41: b.type = Map(2 -> 4, 1 -> 2)

scala> a
res42: scala.collection.mutable.Map[Int,Int] = Map(2 -> 4, 1 -> 2)

scala> def addTo(m: collection.mutable.Map[Int,Int]) { m += (3 -> 9) }
addTo: (m: scala.collection.mutable.Map[Int,Int])Unit

scala> addTo(b)

scala> a
res44: scala.collection.mutable.Map[Int,Int] = Map(2 -> 4, 1 -> 2, 3 -> 9)

Upvotes: 4

Related Questions