1
只是出于好奇,正如标题重新声明之间内存:是否有任何性能或内存分配的差异,如果变量声明和实例化这样的:斯卡拉演出时间/重新初始化和变量
class someClass
def showBoard(typeIs: String){
if (typeIs == "animals"){
val dir: File = new File("animals/");
val blah1= ...;
val blah3 = ...;
}
else if (typeIs == "sports"){
//same variables
}
//same for other categories
而不是这样的:
class someClass
var dir: File = null
var blah = null
var blah2 = null
def showBoard(typeIs: String){
if (typeIs == "animals"){
dir = new File("animals/");
blah = ...;
blah2 = ...;
}
else if (typeIs == "sports"){
//same variables
}
//same thing for the other categories
假设上面的代码运行。
“无记忆差异”。是的,有。在第一种情况下,val会放在堆栈上,当showBoard终止时释放。第二,它们构成了类的一部分,并且(在大多数情况下)将最终堆在堆上 - 只有当对象存在时才会被释放。在某些情况下,这可能也会对性能产生影响。第二个也不是线程(或者甚至递归调用)也是安全的。 –
由于我同意穆拉特回答的后半部分,我也同意保罗的评论。可变状态(var)是不安全的,并且null实例可能会在将来导致问题。而且价值的范围也必须考虑在内。很好的洞察力,谢谢你们!我写了第一个场景,第二个场景只是对这个问题的假设。 –