import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
//获得文件名最快的代码实现方式比较
func main() {
filename := "/root/Desktop/模特唐嘉灵2.jpg"
//方案一
startTime1 := time.Now()
for i := 0; i < 1000000; i++ {
_ = filepath.Base(filename)
}
endTime1 := time.Now()
//方案二
startTime2 := time.Now()
for i := 0; i < 1000000; i++ {
start := strings.LastIndex(filename,string(os.PathSeparator)) + 1
data := []rune(filename)
_ = string(data[start:])
}
endTime2 := time.Now()
//方案三
startTime3 := time.Now()
for i := 0; i < 1000000; i++ {
arr := strings.Split(filename,string(os.PathSeparator))
_ = arr[len(arr)-1]
}
endTime3 := time.Now()
var duration1 time.Duration = endTime1.Sub(startTime1)
var second1 float64 = duration1.Seconds()
var duration2 time.Duration = endTime2.Sub(startTime2)
var second2 float64 = duration2.Seconds()
var duration3 time.Duration = endTime3.Sub(startTime3)
var second3 float64 = duration3.Seconds()
//输出运行耗时:
fmt.Println(second1) //方案一
fmt.Println(second2) //方案二
fmt.Println(second3) //方案三
}
2017/06/22 11:44:01 debugger.go:97: launching process with args: [/root/code/go/src/contoso.org/hello/debug]
API server listening at: 127.0.0.1:2345
2017/06/22 11:44:01 debugger.go:505: continuing
0.025708834 //方案一 ,它最快
0.240723813 //方案二 ,它最慢
0.210655292 //方案三