Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala : Does variable type inference affect performance?

In Scala, you can declare a variable by specifying the type, like this: (method 1)

var x : String = "Hello World"

or you can let Scala automatically detect the variable type (method 2)

var x = "Hello World"

Why would you use method 1? Does it have a performance benefit?
And once the variable has been declared, will it behave exactly the same in all situations wether it has been declared by method 1 or method 2?

like image 789
Marco Prins Avatar asked Oct 30 '14 10:10

Marco Prins


People also ask

What Does type inference mean in Scala?

The Scala compiler can infer the types of expressions automatically from contextual information. Therefore, we need not declare the types explicitly. This feature is commonly referred to as type inference. It helps reduce the verbosity of our code, making it more concise and readable.

Does Scala support type inference mechanism?

The Scala compiler can often infer the type of an expression so you don't have to declare it explicitly.

What would be the type inferred by Scala compiler for variable?

Scala compiler can automatically infer types of each variable declared. If the value of a variable is declared in double-quotes it will automatically be inferred as String. Also, the compiler can infer any value in a single quote is inferred as Char. The compiler, by default it infer any number without decimal as Int.


2 Answers

Type inference is done at compile time - it's essentially the compiler figuring out what you mean, filling in the blanks, and then compiling the resulting code.

What this means is that there can be no runtime cost to type inference. The compile time cost, however, can sometimes be prohibitive and require you to explicitly annotate some of your expressions.

like image 104
Nicolas Rinaudo Avatar answered Oct 15 '22 15:10

Nicolas Rinaudo


You will not have any performance difference using this two variants. They will both be compiled to the same code.

like image 32
rtruszk Avatar answered Oct 15 '22 13:10

rtruszk