Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the performance impact of Scala implicit type conversions?
    primarykey
    data
    text
    <p>In Scala, is there a significant CPU or memory impact to using implicit type conversions to augment a class's functionality vs. other possible implementation choices?</p> <p>For example, consider a silly String manipulation function. This implementation uses string concatenation:</p> <pre><code>object Funky { def main(args: Array[String]) { args foreach(arg =&gt; println("Funky " + arg)) } } </code></pre> <p>This implementation hides the concatenation behind a member method by using an implicit type conversion:</p> <pre><code>class FunkyString(str: String) { def funkify() = "Funky " + str } object ImplicitFunky { implicit def asFunkyString(str: String) = new FunkyString(str) def main(args: Array[String]) { args foreach(arg =&gt; println(arg.funkify())) } } </code></pre> <p>Both do the same thing:</p> <pre><code>scala&gt; Funky.main(Array("Cold Medina", "Town", "Drummer")) Funky Cold Medina Funky Town Funky Drummer scala&gt; ImplicitFunky.main(Array("Cold Medina", "Town", "Drummer")) Funky Cold Medina Funky Town Funky Drummer </code></pre> <p>Is there any performance difference? A few specific considerations:</p> <p>Does Scala inline the implicit calls to the asFunkyString method?</p> <p>Does Scala actually create a new wrapper FunkyString object for each arg, or can it optimize away the extra object allocations?</p> <p>Suppose FunkyString had 3 different methods (funkify1, funkify2, and funkify3), and the body of foreach called each one in succession:</p> <pre><code>println(arg.funkify1()) println(arg.funkify2()) println(arg.funkify3()) </code></pre> <p>Would Scala repeat the conversion 3 times, or would it optimize away the redundant conversions and just do it once for each loop iteration?</p> <p>Suppose instead that I explicitly capture the conversion in another variable, like this:</p> <pre><code>val fs = asFunkyString(arg) println(fs.funkify1()) println(fs.funkify2()) println(fs.funkify3()) </code></pre> <p>Does that change the situation?</p> <p>In practical terms, is broad usage of implicit conversions a potential performance issue, or is it typically harmless?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload