https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
m

Mark

01/29/2020, 3:39 AM
When representing a width-height combo, is there any advantage (other than interactions with other code requiring
Point
) 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.
h

Hitender Pannu

01/29/2020, 4:21 AM
Point is Parcelable and Pair is serializable, Serializable uses reflection and is not as efficient as Parcelable so it really depends on your use case
👍 1
m

Mark

01/29/2020, 4:23 AM
For
Pair<Int, Int>
does the compiler optimise to use two primitive `int`s or two
Integer
objects?
k

Klaas Kabini

01/29/2020, 4:29 AM
The only real advantage for using explicit user defined type such as Point instead of Pair is that you can provide explicit names for the properties of user defined types and use those properties without having to destructure the type. Besides, from code readability perspective, it becomes clear what that structure represents. For example, if I see Point class in codebase it immediately clicks that it represents x,y points in 2D space. By the way width-height combo should be represented using Dimension data class not Point.
h

Hitender Pannu

01/29/2020, 4:29 AM
from what i understand non nullable Int is same as primitive int in java but the nullable int is a boxed object
👍 1
and I am not sure If there is any under the hood optimization is there for Int but Pair is just kind of a container right, It will just hold two reference or values in case of primitives
m

Mark

01/29/2020, 4:32 AM
Do you mean Anko’s
Dimension
or Android’s
Dimension
annotation? Surely only applicable to UI width/height not generic width/height.
k

Klaas Kabini

01/29/2020, 4:35 AM
Dimension is for generic width/height. it is not android specific.
Shapes in 2D space has dimensions of width and height. Unless you want to use width and height to represent something that does not exist in 2D space.
m

Mark

01/29/2020, 4:44 AM
Sure, but the only
Dimension
classes I can see are an annotation class in Android and a data class in Anko.
k

Klaas Kabini

01/29/2020, 5:04 AM
Infact, the Dimension annotation in android is more of a naming misnormer considering its usage which just represents units of measurement. It was supposed to be named something like Unit which is what Jetpack compose did if not mistaken. Besides, naming your data class Dimension would not conflict with the existing annotation. Just like Android, it reuses much of the java API libraries underneath and defines its own API that has classes with similar names as java API. The only differentiator is the package name. In conclusion, it is perfectly fine to name a class with a name already existing in the framework as long as you use a unique package name.
m

Mark

01/29/2020, 5:13 AM
Yes of course. It’s just I thought you were referring to an existing class rather than creating a new one.
t

tseisel

01/29/2020, 9:24 AM
Pair<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)
👍 1
c

Chris Craik

01/29/2020, 11:02 AM
Pair is more expensive, due to autoboxing. Note that on Android, the cost of autoboxing is reduced for small ints, since there's a fixed lookup table of constants, so something to be aware of while measuring. You can verify the cost pretty easily with a benchmark on Android using d.android.com/benchmark
@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
👍 1
but Pair is just kind of a container right, It will just hold two reference or values in case of primitives
Kotlin pair doesn't have any such optimizations in the compiler - it's always references.
g

Gabriel Feo

02/04/2020, 7:58 PM
Adding to what @Klaas Kabini said here
By 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 height
@Mark, I think you could extend
Point
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-maps
m

Mark

02/05/2020, 4:27 AM
Thanks @Gabriel Feo but I think creating your own
data class Dimension(val width: Int, val height: Int)
is the way to go.
g

Gabriel Feo

02/05/2020, 11:03 AM
Certainly your property names are clearer than `Rect`'s 😅