在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/GO/ go函數(shù)用匿名函數(shù)好,還是寫非匿名的好?

go函數(shù)用匿名函數(shù)好,還是寫非匿名的好?

寫go的時候,函數(shù)是像下面的哪種方式好,哪種性能更優(yōu)?
方式一:

package main

import (
    "time"
    "fmt"
)

func main(){
    var getCurrentTime = func() string{
        return time.Now().Format("2006-01-06 15:04:05")
    }
    fmt.Println(getCurrentTime())
}

方式二:

package main

import (
    "time"
    "fmt"
)

func main(){
    fmt.Println(getCurrentTime())
}

func getCurrentTime() string {
    return time.Now().Format("2006-01-06 15:04:05")
}
回答
編輯回答
失魂人
Rob Pike's 5 Rules of Programming
Rule 1: You can't tell where a program is going to spend its time. Bottlenecks occur in surprising places, so don't try to second guess and put in a speed hack until you've proven that's where the bottleneck is.

自己做一下benchmark

func NamedFunc() string {                                
    return getCurrentTime()                              
}                                                        
                                                         
func AnonymousFunc() string {                            
    var f = func() string {                              
        return time.Now().Format("2006-01-06 15:04:05")  
    }                                                    
    return f()                                           
}                                                        
                                                         
func getCurrentTime() string {                           
    return time.Now().Format("2006-01-06 15:04:05")      
}                                                        


var str = ""                                  
                                              
func BenchmarkNamedFunc(b *testing.B) {       
    for i := 0; i < b.N; i++ {                
        str = NamedFunc()                     
    }                                         
}                                             
                                              
func BenchmarkAnonymousdFunc(b *testing.B) {  
    for i := 0; i < b.N; i++ {                
        str = AnonymousFunc()                 
    }                                         
}                                             

我做的結果:

goos: linux
goarch: amd64
BenchmarkNamedFunc-8             5000000           248 ns/op
BenchmarkAnonymousdFunc-8        5000000           248 ns/op
PASS
ok      _/home/singlethread/test/src/definedfunc    3.020s
2017年10月29日 18:03
編輯回答
心沉

按照題主給的例子肯定是方式二更好,但使不使用匿名函數(shù)是看具體的使用場景。更多的時候匿名函數(shù)是和閉包一起使用

2018年5月14日 16:29
編輯回答
懶洋洋

非匿名函數(shù)(命名函數(shù))性能好些
匿名函數(shù)每次都需要重新解釋(解釋這個詞可能不準確)回調,但是命名函數(shù)只需要解釋一次,因此性能會有提升,但是性能差異其實很小,使用的時候視情況而定。

2017年6月23日 16:45