Scala Garbage Collection?

I am relatively new to Scala.

If I have such a design,

sampleFile.map(line => line.map { var myObj = new MyClass(word); myObj.func(); }) 

I create a MyClass object and do something inside the class method ( func() ). I repeat this for all lines in the file (via map ). So, I create an object at each stage of my iteration (for each line). The scope of myObj will be invalid when I start the next iteration (will they be destroyed at the end of the block or will they be lost in memory?). My doubt is when garbage collection is triggered? Also, is it expensive to create an object at each stage of the iteration? Does this have a performance value when the number of rows increases to 1 million?

+7
garbage-collection memory-management scala jvm
source share
2 answers

Your objects should get garbage collection pretty fast (assuming myObj.func() doesn't store a pointer to myObj somewhere else ...). On the JVM, any non-referenced objects should collect garbage - and your last link to the new object disappears as soon as myObj goes out of scope.

Collecting short-lived objects with garbage is usually very cheap and efficient, so you probably should not worry about it (at least until you have benchmarks / performance problems that prove otherwise ....)

In particular, since you seem to be doing IO (reading from a sample file?), I expect that the overhead of GC is negligible compared to the cost of disk I / O.

+7
source share

Garbage collection rests with the JVM, not Scala. The exact details depend on which JVM you are using. There is no specific time at which garbage collection starts; The JVM tries to do this when it is convenient or necessary.

Someone more knowledgeable than me about the GC algorithms and JVM tuning can probably give you some specific explanation to solve your performance problems, but overall I would say that you just have to trust that the JVM is very good at picking garbage "reasonably."

+1
source share

All Articles