Skip to content

Commit 4715b53

Browse files
author
Tao Wen
committed
optimize fixed size array
1 parent 9955b67 commit 4715b53

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

generator/encoder.go

+18
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,13 @@ func encodeAnonymousStruct(structType *ast.StructType) string {
8383
}
8484

8585
func encodeArray(arrayType *ast.ArrayType) {
86+
if arrayType.Len != nil {
87+
arrayLen, err := strconv.ParseInt(nodeToString(arrayType.Len), 10, 64)
88+
if err == nil && arrayLen < 10 {
89+
encodeFixedSizeArray(arrayType, int(arrayLen))
90+
return
91+
}
92+
}
8693
_l(" if len(val) == 0 {")
8794
_l(" stream.WriteEmptyArray()")
8895
_l(" } else {")
@@ -95,6 +102,17 @@ func encodeArray(arrayType *ast.ArrayType) {
95102
_l(" }")
96103
}
97104

105+
func encodeFixedSizeArray(arrayType *ast.ArrayType, length int) {
106+
_l(" stream.WriteArrayHead()")
107+
for i := 0; i < length; i++ {
108+
if i != 0 {
109+
_l(" stream.WriteMore()")
110+
}
111+
genEncodeStmt(arrayType.Elt, fmt.Sprintf("val[%d]", i))
112+
}
113+
_l(" stream.WriteArrayTail()")
114+
}
115+
98116
func encodeMap(mapType *ast.MapType) {
99117
_l(" if len(val) == 0 {")
100118
_l(" stream.WriteEmptyObject()")

value_tests/NestedArray_json.go

+3-8
Original file line numberDiff line numberDiff line change
@@ -66,14 +66,9 @@ func NestedArray_json_marshal(stream *jsoniter.Stream, val NestedArray) {
6666
}
6767
}
6868
func NestedArray_array2_json_marshal (stream *jsoniter.Stream, val [2]float64) {
69-
if len(val) == 0 {
70-
stream.WriteEmptyArray()
71-
} else {
7269
stream.WriteArrayHead()
73-
for i, elem := range val {
74-
if i != 0 { stream.WriteMore() }
75-
stream.WriteFloat64(elem)
76-
}
70+
stream.WriteFloat64(val[0])
71+
stream.WriteMore()
72+
stream.WriteFloat64(val[1])
7773
stream.WriteArrayTail()
78-
}
7974
}

0 commit comments

Comments
 (0)