1 /*
2  * Copyright 2021 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 import Benchmark
18 import CoreFoundation
19 import FlatBuffers
20 
21 benchmark("10Strings") {
22   var fb = FlatBufferBuilder(initialSize: 1<<20)
23   for _ in 0..<1_000_000 {
24     _ = fb.create(string: "foobarbaz")
25   }
26 }
27 
28 benchmark("100Strings") {
29   var fb = FlatBufferBuilder(initialSize: 1<<20)
30   for _ in 0..<1_000_000 {
31     _ = fb.create(string: str)
32   }
33 }
34 
35 benchmark("FlatBufferBuilder.add") {
36   var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
37   for _ in 0..<1_000_000 {
38     let off = fb.create(string: "T")
39     let s = fb.startTable(with: 4)
40     fb.add(element: 3.2, def: 0, at: 2)
41     fb.add(element: 4.2, def: 0, at: 4)
42     fb.add(element: 5.2, def: 0, at: 6)
43     fb.add(offset: off, at: 8)
44     _ = fb.endTable(at: s)
45   }
46 }
47 
48 benchmark("structs") {
49   let structCount = 1_000_000
50 
51   let rawSize = ((16 * 5) * structCount) / 1024
52 
53   var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600))
54 
55   var offsets: [Offset] = []
56   for _ in 0..<structCount {
57     fb.startVector(
58       5 * MemoryLayout<AA>.size,
59       elementSize: MemoryLayout<AA>.alignment)
60     for _ in 0..<5 {
61       _ = fb.create(struct: AA(a: 2.4, b: 2.4))
62     }
63     let vector = fb.endVector(len: 5)
64     let start = fb.startTable(with: 1)
65     fb.add(offset: vector, at: 4)
66     offsets.append(Offset(offset: fb.endTable(at: start)))
67   }
68   let vector = fb.createVector(ofOffsets: offsets)
69   let start = fb.startTable(with: 1)
70   fb.add(offset: vector, at: 4)
71   let root = Offset(offset: fb.endTable(at: start))
72   fb.finish(offset: root)
73 }
74 
75 let str = (0...99).map { _ -> String in "x" }.joined()
76 
77 @usableFromInline
78 struct AA: NativeStruct {
79   public init(a: Double, b: Double) {
80     self.a = a
81     self.b = b
82   }
83   var a: Double
84   var b: Double
85 }
86 
87 Benchmark.main()
88