錯誤的方式
試圖通過拷貝*big.Int指針所指的結(jié)構(gòu):
a := big.NewInt(10)
b := new(big.Int)
*b = *a
這種方式是錯誤的,因為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)部實現(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測試
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)
}
}
性能對比
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
比較兩次運行的結(jié)果,發(fā)現(xiàn):
-
BenchmarkBigIntCopyBytes有額外的內(nèi)存分配,其它兩個方法則沒有 - 當(dāng)
big.Int值變大時,BenchmarkBigIntCopyBytes分配的內(nèi)存增加,性能變差,結(jié)果BenchmarkBigIntCopier接近,甚至還差一點 -
BenchmarkBigIntCopyByAdd是性能最好的,沒有額外的內(nèi)存分配,且耗時穩(wěn)定
結(jié)論
+ 0 是最好的選擇