在学习中了解到defer相比没有使用defer会消耗部分时间,所以测试了下,使用与不使用defer的性能测试,通过实验,defer影响程序的速度基本可以忽略不计。
package main
import (
"time"
"fmt"
)
func main() {
t1 := time.Now()
for i := 0;i < 1000000;i++ {
test1()
}
et1 := time.Since(t1)
fmt.Println("Run time: ", et1)
t2 := time.Now()
for i := 0;i < 1000000;i++ {
test2()
}
et2 := time.Since(t2)
fmt.Println("Run time: ", et2)
t3 := time.Now()
for i := 0;i < 1000000;i++ {
test3()
}
et3 := time.Since(t3)
fmt.Println("Run time: ", et3)
}
func test1() {
func() {
for i := 0;i <10;i++{
}
}()
}
func test2() {
defer func() {
for i := 0;i <10;i++{
}
}()
}
func test3() {
for i := 0;i <10;i++{
}
}
Run time: 11.0081ms
Run time: 70.0497ms
Run time: 11.0076ms