golang if-else 和 switch-fallthrough 比較
阿新 • • 發佈:2018-12-30
經過比較 if 時間更快!
package main import ( "fmt" "math/rand" "time" ) func main() { n := 100000000 st := time.Now() test1(n) fmt.Println(time.Since(st)) st = time.Now() test2(n) fmt.Println(time.Since(st)) } func test2(n int) { f := 0 r := rand.Intn(10) for i := 0; i < n; i++ { if r == 0 || r == 1 || r == 2 || r == 3 || r == 4 || r == 5 || r == 6 || r == 7 || r == 8 || r == 9 { f += r } r = rand.Intn(10) } } func test1(n int) { f := 0 r := rand.Intn(10) for i := 0; i < n; i++ { switch r { case 0: fallthrough case 1: fallthrough case 2: fallthrough case 3: fallthrough case 4: fallthrough case 5: fallthrough case 6: fallthrough case 7: fallthrough case 8: fallthrough case 9: fallthrough default: f += r } r = rand.Intn(10) } }
4.608s
4.336s