錯(cuò)誤的方式
試圖通過拷貝*big.Int
指針?biāo)傅慕Y(jié)構(gòu):
a := big.NewInt(10)
b := new(big.Int)
*b = *a
這種方式是錯(cuò)誤的,因?yàn)?code>big.Int結(jié)構(gòu)內(nèi)部有slice
闰非,拷貝結(jié)構(gòu)的話內(nèi)部的slice
仍然是共享內(nèi)存膘格。
正確的方式
1.拷貝Bytes
思想:
序列化成[]bytes,然后拷貝
func BenchmarkBigIntCopyBytes(b *testing.B) {
b.ReportAllocs()
old, _ := new(big.Int).SetString("100000000222222222222222222220000000000000000000", 10)
new := new(big.Int)
for i := 0; i < b.N; i++ {
new.SetBytes(old.Bytes())
}
}
2.反射賦值
思想:
通過反射賦值
func BenchmarkBigIntCopier(b *testing.B) {
b.ReportAllocs()
old, _ := new(big.Int).SetString("100000000222222222222222222220000000000000000000", 10)
new := new(big.Int)
for i := 0; i < b.N; i++ {
// "github.com/jinzhu/copier"
copier.Copy(new, old)
}
}
copier
內(nèi)部實(shí)現(xiàn)使用了reflect
财松。
3. +0
思想
new = old = old + 0
func TestCopyByAdd(t *testing.T) {
old, _ := new(big.Int).SetString("100000000222222222222222222220000000000000000000", 10)
new := new(big.Int)
// new = old = old + 0
new.Add(old, new)
if old.Cmp(new) != 0 {
t.FailNow()
}
new.Add(new, big.NewInt(1))
t.Logf("old:%v,new:%v", old, new)
if old.Cmp(new) >= 0 {
t.FailNow()
}
}
Benchmark測(cè)試
func BenchmarkBigIntCopyByAdd(b *testing.B) {
b.ReportAllocs()
old, _ := new(big.Int).SetString("100000000222222222222222222220000000000000000000", 10)
new := new(big.Int)
for i := 0; i < b.N; i++ {
// new = old = old + 0
new.Add(old, new)
}
}
性能對(duì)比
big.Int = 10
BenchmarkBigIntCopier-8 30000000 62.5 ns/op 0 B/op 0 allocs/op
BenchmarkBigIntCopyBytes-8 30000000 46.7 ns/op 8 B/op 1 allocs/op
BenchmarkBigIntCopyByAdd-8 100000000 20.8 ns/op 0 B/op 0 allocs/op
big.Int = 100000000222222222222222222220000000000000000000
BenchmarkBigIntCopier-8 30000000 60.8 ns/op 0 B/op 0 allocs/op
BenchmarkBigIntCopyBytes-8 20000000 69.1 ns/op 32 B/op 1 allocs/op
BenchmarkBigIntCopyByAdd-8 100000000 22.1 ns/op 0 B/op 0 allocs/op
比較兩次運(yùn)行的結(jié)果瘪贱,發(fā)現(xiàn):
-
BenchmarkBigIntCopyBytes
有額外的內(nèi)存分配,其它兩個(gè)方法則沒有 - 當(dāng)
big.Int
值變大時(shí)游岳,BenchmarkBigIntCopyBytes
分配的內(nèi)存增加政敢,性能變差其徙,結(jié)果BenchmarkBigIntCopier
接近胚迫,甚至還差一點(diǎn) -
BenchmarkBigIntCopyByAdd
是性能最好的,沒有額外的內(nèi)存分配唾那,且耗時(shí)穩(wěn)定
結(jié)論
+ 0
是最好的選擇