1
1
package json_diff
2
2
3
3
import (
4
+ "bytes"
5
+ "encoding/gob"
6
+ "fmt"
4
7
"io/ioutil"
8
+ "os"
9
+ "runtime/pprof"
5
10
"testing"
11
+ "time"
6
12
)
7
13
8
14
func TestDeepCopy_emptyObject (t * testing.T ) {
@@ -22,7 +28,7 @@ func TestDeepCopy_emptyObject(t *testing.T) {
22
28
}
23
29
24
30
func TestDeepCopy (t * testing.T ) {
25
- fileName := "./test_data/deepcopy_test.json"
31
+ fileName := "./test_data/deepcopy_test/deepcopy_test .json"
26
32
input , err := ioutil .ReadFile (fileName )
27
33
if err != nil {
28
34
t .Error ("fail to open the " , fileName )
@@ -69,3 +75,60 @@ func TestDeepCopy(t *testing.T) {
69
75
t .Errorf ("change source object: %v" , cpof .Value )
70
76
}
71
77
}
78
+
79
+ func oldDeepCopy (dst , src interface {}) error {
80
+ var buf bytes.Buffer
81
+ if err := gob .NewEncoder (& buf ).Encode (src ); err != nil {
82
+ return err
83
+ }
84
+ return gob .NewDecoder (bytes .NewBuffer (buf .Bytes ())).Decode (dst )
85
+ }
86
+
87
+ func TestDeepCopy_speed (t * testing.T ) {
88
+ fileName := "./test_data/deepcopy_test/deepcopy_speed_test.json"
89
+ input , err := ioutil .ReadFile (fileName )
90
+ if err != nil {
91
+ t .Error ("fail to open the " , fileName )
92
+ }
93
+ srcNode , _ := Unmarshal (input )
94
+ deepCopySpeedTestHelper (srcNode , t , 1000 , true , true )
95
+ deepCopySpeedTestHelper (srcNode , t , 1000 , true , false )
96
+ deepCopySpeedTestHelper (srcNode , t , 1000 , false , true )
97
+ }
98
+
99
+ func deepCopySpeedTestHelper (srcNode * JsonNode , t * testing.T , loop int , doOld , doNew bool ) {
100
+ path := "test_data/deepcopy_test/pprof_result"
101
+ name := ""
102
+ var err error
103
+ if doOld && doNew {
104
+ name = fmt .Sprintf ("compared_cpu_profile_%d" , time .Now ().UnixNano ())
105
+ } else if doOld {
106
+ name = fmt .Sprintf ("old_func_cpu_profile_%d" , time .Now ().UnixNano ())
107
+ } else if doNew {
108
+ name = fmt .Sprintf ("new_func_cpu_profile_%d" , time .Now ().UnixNano ())
109
+ }
110
+ f , err := os .Create (fmt .Sprintf ("%s/%s" , path , name ))
111
+ if err != nil {
112
+ t .Errorf ("can not Start CPU Profile: %v" , err )
113
+ }
114
+ _ = pprof .StartCPUProfile (f )
115
+ defer pprof .StopCPUProfile ()
116
+ startTime := time .Now ().UnixNano ()
117
+ for i := 0 ; i < loop ; i ++ {
118
+ if doOld {
119
+ oldCopyRes := new (JsonNode )
120
+ err = oldDeepCopy (oldCopyRes , srcNode )
121
+ if err != nil {
122
+ t .Errorf ("fail to copy by old function: %v" , err )
123
+ }
124
+ }
125
+ if doNew {
126
+ _ , err = DeepCopy (srcNode )
127
+ if err != nil {
128
+ t .Errorf ("fail to copy by new function: %v" , err )
129
+ }
130
+ }
131
+ }
132
+ spend := (time .Now ().UnixNano () - startTime ) / 1000000
133
+ fmt .Printf ("do %d loops spend %v ms \n " , loop , spend )
134
+ }
0 commit comments