天天看點

[Scala基礎]--call by name和call by value的差別

scala版本:scala-2.10.5

一、前言

這裡涉及到Scala的匿名函數、高階函數、閉包和Jvm相關的知識,有關内容請查閱這本pdf書籍:

Scala Cookbook - Recipes for Object-Oriented and Functional Programming_Alvin Alexander_2013

在Spark的源碼中,大量使用call by name 的調用,減少了函數的調用次數,大大提高了軟體性能。

二、舉例

  • func():傳回值是Int,沒有參數
  • callByValue(x:Int):傳回值是Unit,傳入Int類型的值
  • callByName(x:=>Int):傳回值是Unit,傳入的是一個匿名函數(該函數傳入的參數為空,傳回值是Int)
def func(): Int ={
    println("Compute some stuff...")
  23 // return value
}

def callByValue(x:Int)={
  println(s"1 first : $x ")
  println(s"2 second : $x ")
}

def callByName(x: => Int)={
  println(s"1 first : $x ")
  println(s"2 second : $x ")
}

test("2018年5月23日14:16:30 測試call by name 和call by value的差別"){
  callByName(func())
  println("---------------------------------")
  callByValue(func())
}      

運作結果:

Testing started at 14:31 ...
Compute some stuff...
1 first : 23 
Compute some stuff...
2 second : 23 
---------------------------------
Compute some stuff...
1 first : 23 
2 second : 23      

現象:

1、callByName:func()被調用了2次

2、callByValue:func()被調用了1次

差別:

1、call-by-name:在調用函數時計算的(即需要時,才會調用)。