Closed okJiang closed 2 weeks ago
Seem lots of codes used json.Unmarshal
in Clone
🤔 ref https://github.com/tikv/pd/pull/5480
json.Unmarshal
and Marshal
can indeed conveniently implement Clone
without needing to worry about pointer types within the struct. But compared to simple assignment, it does take a bit more time.
Perhaps we should avoid using the Unmarshal/Marshal
method for simple structs and keep it unchanged for complex ones.
Just did some bench testing on a simple structure, and found that the performance difference isn't that big...
func BenchmarkCloneWithJSON(b *testing.B) {
c := &RaftCluster{
meta: &metapb.Cluster{
Id: 1,
MaxPeerCount: 3,
},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = func() *metapb.Cluster {
return typeutil.DeepClone(c.meta, core.ClusterFactory)
}
}
}
func BenchmarkCloneWithAssignment(b *testing.B) {
c := &RaftCluster{
meta: &metapb.Cluster{
Id: 1,
MaxPeerCount: 3,
},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = func() *metapb.Cluster {
clone := *c.meta
return &clone
}
}
}
BenchmarkCloneWithJSON-8 1000000000 0.3143 ns/op 0 B/op 0 allocs/op
BenchmarkCloneWithAssignment-8 1000000000 0.3142 ns/op 0 B/op 0 allocs/op
Enhancement Task
https://github.com/tikv/pd/blob/c1d422ec4924799a5ff7da6606644959e339f1c0/pkg/schedule/placement/rule.go#L92-L93