Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala. Too much small functions, too many classes?

Tags:

scala

I am a Scala newcomer, but have some Java background.

When writing Scala code it is useful to deal with Option parameter in such style:

val text = Option("Text")
val length = text.map(s => s.size)

but each s => s.size as I know brings a new Function1[A, B]. And if I do for example 8 such conversions it will bring 8 additional classes. When binding forms I use such snippets very heavily, so the question is:

Should I use it less and, maybe substitute it with an if-notation, or is such class-flood not critical for the JVM, or maybe the Scala compiler does some kind of magic?

Update: a maybe more concrete example is:

case class Form(name: Option[String], surname: Option[String])
val bindedForm = Form(Option("John"), Option("Smith"))
val person = new Person
bindedForm.name.foreach(a => person.setName(a))
bindedForm.surname.foreach(a => person.setSurname(a))

will it produce two different Function1[String, String] classes? What if there are hundreds of such conversions?

like image 340
Alex Povar Avatar asked Jan 15 '23 18:01

Alex Povar


1 Answers

If you are developing for Android, then you're probably going to run the code using Dalvik, which has an annoying 64k method limitation (though there are ways around it). Since each class requires a couple of methods (constructor and apply), this can be a problem.

Otherwise, classes on the Sun/Oracle JVM go into PermGen space, which you can adjust when launching the JVM if you really need to. It really doesn't matter. Yes, you'll have lots of classes, maybe tens of thousands, but the JVM can handle it fine (at least if you're willing to give it a heads-up about what to expect). Unless you know you're very likely to run into some unusual constraint, this is not something you should be worrying much about.

Far more often one might be worried that creating all those functions has a performance penalty--but if you're not actually running into that penalty now, don't worry about that either; this is something that the Scala compiler can in principle fix, and it's getting cleverer all the time. So just write code the idiomatic way and unless it's a big performance problem now, just hope that the compiler will come save you. There's a decent chance it will, and an even better chance that you'll find it easier to write it the "right" way and then refactor for performance where needed than to adopt a policy of using a more awkward construct just in case there might be a problem. Of course, there are some places that you may know in advance are certain to be a bottleneck, like wrapping each byte you read from a huge file in an option, but aside from blatant stuff like that, you're better off acting reactively to known problems than proactively avoiding closures.

like image 176
Rex Kerr Avatar answered Jan 23 '23 06:01

Rex Kerr