1+ /*
2+ * Copyright 2024 JetBrains s.r.o.
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+ package microBenchmarks
18+
19+ import kotlinx.benchmark.*
20+
21+ @State(Scope .Benchmark )
22+
23+
24+ class BoxingBenchmark {
25+ @Benchmark
26+ fun integerTypeBoxing (): Int {
27+ val size = BENCHMARK_SIZE
28+ var box: Int? = 42
29+ var unbox: Int = 24
30+ for (i in 0 .. size) {
31+ val value: Int = box!!
32+ box = unbox
33+ unbox = value
34+ }
35+ return box.hashCode() + unbox.hashCode()
36+ }
37+
38+ @Benchmark
39+ fun booleanTypeBoxing (): Int {
40+ val size = BENCHMARK_SIZE
41+ var box: Boolean? = true
42+ var unbox: Boolean = false
43+ for (i in 0 .. size) {
44+ val value: Boolean = box!!
45+ box = unbox
46+ unbox = value
47+ }
48+ return box.hashCode() + unbox.hashCode()
49+ }
50+
51+ @Benchmark
52+ fun referenceTypeVarClosure (): Int {
53+ val size = BENCHMARK_SIZE * 10
54+ var varBox1: Any = Any ()
55+ var varBox2: Any = Any ()
56+ val closure = {
57+ val value = varBox1
58+ varBox1 = varBox2
59+ varBox2 = value
60+ }
61+
62+ for (i in 0 .. size) {
63+ closure()
64+ }
65+
66+ return varBox1.hashCode() + varBox2.hashCode()
67+ }
68+
69+ @Benchmark
70+ fun integerTypeVarClosure (): Int {
71+ val size = BENCHMARK_SIZE * 10
72+ var varBox1: Int = 42
73+ var varBox2: Int = 24
74+ val closure = {
75+ val value = varBox1
76+ varBox1 = varBox2
77+ varBox2 = value
78+ }
79+
80+ for (i in 0 .. size) {
81+ closure()
82+ }
83+
84+ return varBox1.hashCode() + varBox2.hashCode()
85+ }
86+ }
0 commit comments