1

Scala relies on java.lang.String for it's String operations, however, it enriches the java string class by adding other methods such as .intersect among others Same goes for the int wrapper (Int) in java, there's also the RichInt class.

I realize that the following code:

val stringOne: String = "teststring"
val stringTwo: String = "string"
stringOne.intersect(stringTwo)

will cause the scala compiler to kind of cast stringOne to the StringOps class so that it has access to method intersect

I'm concerned that this could result in serious computational costs So can anyone tell me if this is true and if so, are there ways to optimize or avoid this situation?

I hope my question makes sense, i have read several books, but none addresses these concerns Thanks. :)

EDIT: A similar question has been asked and answered here I would appreciate it if anyone could address this from the memory angle as well

Community
  • 1
  • 1
SamAko
  • 3,485
  • 7
  • 41
  • 77
  • Have you heard of implicit conversions? If no - I recommend you to read about subject, it is related to your question. – dmitry Sep 25 '13 at 17:05
  • i know implicit conversions are those handled by the compiler without you doing it yourself in code e.g in java Employer em = new Employee(); Manager mg = (Manager) em is an explicit conversion. No? – SamAko Sep 25 '13 at 17:31

1 Answers1

2

In general, there can be performance impacts from implicit conversions (e.g. for a long time .isNaN was ~50% slower than java.lang.Double.isNaN). However, if the class being converted to is a value class, the JIT compiler has a much easier time removing the remaining overhead (usually there is none; you can still retain some overhead if you have one implicit conversion use another which uses another etc.--the JIT compiler gives up before removing the entire chain of calls).

In any case, that's not the primary concern here. intersect is a generic method so it will box all of the characters in the string. That will slow things down immensely (probably 5x or so) compared to a method that is custom-designed to take only Char.

The way to tell these things is to look through the Scaladocs and see where the implementation is. intersect is not out in the leaf (StringOps); it's all the way back in SeqLike, which doesn't know anything about characters specifically. (Well, okay, to be really sure you need to look at the source code and/or benchmark, but you can usually get a good idea from the definition site listed in Scaladoc.)

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407