Hullaballoonatic
12/21/2019, 4:58 PMclass Polygon(val vertices: List<Point>) {
val height by lazy { vertices.maxBy(Point::y)!!.y - vertices.minBy(Point::y)!!.y }
val width by lazy { vertices.maxBy(Point::x)!!.x - vertices.minBy(Point::x)!!.x }
val edges by lazy { (points + points.first()).zipWithNext(::Line) }
val area by lazy { edges.sumByDouble { (cur, next) -> cur.x * next.y - cur.y * next.x } / 2 } // shoelace method
val centroid by lazy {
edges.reduce(Point.Origin) { acc, (cur, next) ->
acc + ((cur + next) * (cur.x * next.y - next.x * cur.y))
}
}
// etc
}
Afaik
Advantages:
• faster instantiation
• instance fields that are never accessed are never computed
Disadvantages:
• instance fields computed when first accessed, which may be a performance heavy time
General questions:
• Does lazy<T>
occupy more space than T
? Answered: yes, it creates an object and a lambda in memory
• Is there some kind of performance impact at initialization for lazy
that may make for a negligible difference in impact for many fields?
• Am I an idiot, and unless something is rarely accessed, I should just completely avoid using lazy
?Dominaezzz
12/21/2019, 5:06 PMlazy<T>
creates a Lazy<T>
object, it also uses atomics by default which might be impactful.Dominaezzz
12/21/2019, 5:07 PMHullaballoonatic
12/21/2019, 5:07 PMHullaballoonatic
12/21/2019, 5:08 PMMark Murphy
12/21/2019, 5:22 PMfaster instantiationNot necessarily, at least in any meaningful fashion. Consider:
val foo by lazy { 2 + 2 }
I would not assume that calling lazy()
and instantiating the Lazy<Int>
will be less time than adding two Int
values. While this is an obviously-contrived example, there is some minimum threshold for which lazy { }
will be faster.
unless something is rarely accessed, I should just completely avoid usingThe other scenario that I have seen is using?lazy
lazy { }
as an alternative to lateinit var
for things that you cannot initialize up front but are sure[1] to be able to initialize when you first need them. In Android app development, for example, you will see some people use val button by lazy { findViewById<Button>(R.id.button) }
, because we cannot call findViewById()
when the activity is being constructed, but by the time we would reference button
, findViewById()
certainly[1] works.
[1] for certain values of "sure" and "certainly"Adam Powell
12/21/2019, 5:26 PMHullaballoonatic
12/21/2019, 5:28 PMAdam Powell
12/21/2019, 5:28 PMlazy
look like magic at firsttschuchort
12/21/2019, 5:29 PMtschuchort
12/21/2019, 5:30 PMHullaballoonatic
12/21/2019, 5:32 PMlazy
is when I need to compute the initial value of a field across multiple lines of code.
Instead, do you prefer init
or run
? I prefer run
Adam Powell
12/21/2019, 5:34 PMAdam Powell
12/21/2019, 5:36 PMDico
12/21/2019, 7:15 PMjimn
12/22/2019, 1:57 AMDico
12/22/2019, 8:03 AMHullaballoonatic
01/05/2020, 3:34 PMHullaballoonatic
01/05/2020, 3:34 PMjimn
01/05/2020, 4:09 PMhttp://i.imgur.com/k0t1e.png▾