-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版本的作品如預期,即字節碼已經被優化。