Golang高效地拷贝big.Int

栏目: Go · 发布时间: 7年前

内容简介:思想:序列化成[]bytes,然后拷贝思想:

可以选择的方法

拷贝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())
    }
}

反射赋值

思想:

通过反射赋值

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 内部实现使用了 reflect

+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

比较两次运行的结果,发现:

  • BenchmarkBigIntCopyBytes 有额外的内存分配,其它两个方法则没有
  • big.Int 值变大时, BenchmarkBigIntCopyBytes 分配的内存增加,性能变差,结果 BenchmarkBigIntCopier 接近,甚至还差一点
  • BenchmarkBigIntCopyByAdd 是性能最好的,没有额外的内存分配,且耗时稳定

结论

BenchmarkBigIntCopyByAdd 是最好的选择。


以上所述就是小编给大家介绍的《Golang高效地拷贝big.Int》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

中国机器人

中国机器人

[中]王鸿鹏、[中]马娜 / 辽宁人民出版社 / 2017-1-1 / 48.00元

本书对中国机器人领域的发展历史做了引人入胜的介绍,中国机器人成长的过程也是中国经济由弱到强的历程。本书实际是选择了一个独特的视角来解读中国数十年的政治、经济、国家战略问题。中国的未来充满了多重可能性,本书对想了解中国当代与未来发展战略的读者是难得的读本,对智能制造这一当今世界*受关注的高科技领域在战略层面和科技伦理层面进行了深入地剖析和思考,其中提出的诸多前沿性观点是全球都将面对的问题,对中国科学......一起来看看 《中国机器人》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具