-1

在下面的Scala代码片段中,我试图确保尽可能多的表达式是“预编译”的,以便函数文本的最终完整应用程序引发尽可能少的cpu-尽可能循环。即,我希望确保在函数文字赋值时评估if条件,而不是在将函数文字应用于未绑定参数时进行评估。Scala函数值部分评估歧义(内联?)

private val tokenFilterFactory: TokenStream => TokenStream = 
    if(augment) { 
    new AugmentingStemmingTokenFilter(_, markStems, bitPos, stemmerFactory()) 
    } 
    else { 
    new ReplacingStemmingTokenFilter(_, markStems, bitPos, stemmerFactory()) 
    } 

我想是,然后向功能字面了大量的时间,像 tokenFilterFactory(的TokenStream)

我的问题:将有条件if(augment)每隔应用于文字的功能时(执行坏的),还是只能在函数文字被定义/赋值时执行一次?背景:斯卡拉2.11

等价地,是上述VAL-任务运行时当量(仅WRT的评价,而不是“可转让”)以下的片段:

private var tokenFilterFactory: TokenStream => TokenStream = _ 
if(augment) { 
    tokenFilterFactory = new AugmentingStemmingTokenFilter(_, markStems, bitPos, stemmerFactory()) 
} 
else { 
    tokenFilterFactory = new ReplacingStemmingTokenFilter(_, markStems, bitPos, stemmerFactory()) 
} 

也就是说,我想的以前的代码像后者一样行事。这是事实吗?

我意识到我可以试试一些printlns,但也许有人可以点亮任何限制字节码优化的影响这种情况?

+1

“我知道我可以试试它”。 – Dima

+0

感谢您的动力:-) –

回答

0
def condition(): Boolean = { 
    println("conditional evaluated") 
    true 
} 
private val intModifier: Int => Int = 
    if(condition()) { 
    _ + 1 
    } else { 
    _ - 1 
    } 

intModifier(1) 
intModifier(2) 

输出:

condition: condition[]() => Boolean 



conditional evaluated 
intModifier: Int => Int = <function1> 


res0: Int = 2 
res1: Int = 3 

所以val版本的作品如预期,即字节码已经被优化。