2017-07-29 59 views
0

我遇到過不同的方法將變量合併到Go中的錯誤消息中。在下面的例子中,哪種方式是慣用的?有更好的選擇嗎?在錯誤消息中包含數據的慣用方式是什麼?

當事情開始中斷時更安全嗎?例如,當剩餘的內存很少時,分配較少字節的選項將更可取。

如果我們需要產生很多錯誤,哪個更快?

完整的可運行代碼可以在Go Play Space或官方Go Playground中看到。

func f() error { 
    return SepError("Sepuled " + strconv.Itoa(n) + " sepulcas " + strconv.Itoa(t) + 
     " times each") 
} 

func g() error { 
    return SepError(strings.Join([]string{ 
     "Sepuled", strconv.Itoa(n), "sepulcas", strconv.Itoa(t), "times each"}, " ")) 
} 

func h() error { 
    return SepError(fmt.Sprintf("Sepuled %d sepulcas %d times each", n, t)) 
} 

回答

3

除非你有很少的記憶,或將要產生大量的這些錯誤,我不會擔心它。就慣用Go而言,我會選擇h()選項,因爲它更易於閱讀。

這裏的好處是,使用分配,內存和速度可以用一些簡單的基準`去測試-bench的

func BenchmarkF(b *testing.B) { 
    for i := 0; i <= b.N; i++ { 
     f() 
    } 
} 

func BenchmarkG(b *testing.B) { 
    for i := 0; i <= b.N; i++ { 
     g() 
    } 
} 

func BenchmarkH(b *testing.B) { 
    for i := 0; i <= b.N; i++ { 
     h() 
    } 
} 

輸出進行測試。 -benchmem

BenchmarkF-8 10000000   169 ns/op   72 B/op   4 allocs/op 
BenchmarkG-8 10000000   204 ns/op   120 B/op   5 allocs/op 
BenchmarkH-8  5000000   237 ns/op   80 B/op   4 allocs/op 

正如你所看到的,f()是最快的,使用最少的內存,並且是並列分配最少。這也是不值得的(在我看來)額外的可讀性成本。

相關問題