go函数用匿名函数好,还是写非匿名的好?

写go的时候,函数是像下面的哪种方式好,哪种性能更优?
方式一:

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")
}
阅读 5.5k
3 个回答

非匿名函数(命名函数)性能好些
匿名函数每次都需要重新解释(解释这个词可能不准确)回调,但是命名函数只需要解释一次,因此性能会有提升,但是性能差异其实很小,使用的时候视情况而定。

按照题主给的例子肯定是方式二更好,但使不使用匿名函数是看具体的使用场景。更多的时候匿名函数是和闭包一起使用

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
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题