Mark
01/29/2020, 3:39 AMPoint
) to using Point
instead of Pair<Int, Int>
? I’m preferring Pair
(because of destructuring and also not being Android-specific) but since I’m creating potentially tens of thousands of these objects, I wanted to check if there is any performance issues.Hitender Pannu
01/29/2020, 4:21 AMMark
01/29/2020, 4:23 AMPair<Int, Int>
does the compiler optimise to use two primitive `int`s or two Integer
objects?Klaas Kabini
01/29/2020, 4:29 AMHitender Pannu
01/29/2020, 4:29 AMMark
01/29/2020, 4:32 AMDimension
or Android’s Dimension
annotation? Surely only applicable to UI width/height not generic width/height.Klaas Kabini
01/29/2020, 4:35 AMMark
01/29/2020, 4:44 AMDimension
classes I can see are an annotation class in Android and a data class in Anko.Klaas Kabini
01/29/2020, 5:04 AMMark
01/29/2020, 5:13 AMtseisel
01/29/2020, 9:24 AMPair<A, B>
is a class with 2 generic parameters. Due to type erasure on the JVM, this class is compiled as Pair
with two fields of type Any
.
So there is no compiler optimization for it : Pair<Int, Int>
uses boxed ints (Integer
). If you use a lot of them, I suggest that you define your own class, it's only one line :
data class Dimension(val width: Int, val height: Int)
Chris Craik
01/29/2020, 11:02 AM@get:Rule
val benchmarkRule = BenchmarkRule()
@Test
fun pair() = benchmarkRule.measureRepeated {
Pair(10000, 20000)
}
@Test
fun point() = benchmarkRule.measureRepeated {
Point(10000, 20000)
}
Results on Pixel1, running Q:
benchmark: 222 ns ExampleBenchmark.pair
benchmark: 48 ns ExampleBenchmark.point
but Pair is just kind of a container right, It will just hold two reference or values in case of primitivesKotlin pair doesn't have any such optimizations in the compiler - it's always references.
Gabriel Feo
02/04/2020, 7:58 PMBy the way width-height combo should be represented using Dimension data class not Point.I believe the width+height combo would be represented by
Rect
. Point
is a single coordinate, and Rect
is pair of coordinates, thus you'd get width and heightPoint
and Rect
with componentN
and get destructuring declarations without the cost of autoboxing: https://kotlinlang.org/docs/reference/multi-declarations.html#example-destructuring-declarations-and-mapsMark
02/05/2020, 4:27 AMdata class Dimension(val width: Int, val height: Int)
is the way to go.Gabriel Feo
02/05/2020, 11:03 AM