Some of my lessons learned after digging into emit...
# javascript
m
Some of my lessons learned after digging into emitted JS code for optimization 😅 I’ll add to the list as I learn more. • Avoid
x.toString()
. Use
"$x"
. The former cannot be optimized by Terser. • Avoid
Number
. Cannot be optimized by Terser. • Avoid
String.isEmpty()
and
String.isNotEmpty()
. Unnecessarily imports
CharSequence
code. Use
== ""
and
!= ""
. • Avoid
StringBuilder
. Imports heaps of code. I’ve made a cheap alternative: https://gist.github.com/fluidsonic/473758c30dd084042905e77c5ebd0374 • Avoid
Long
if possible. Uses a custom JS class fo Kotlin and cannot be optimized by Terser. • Avoid `print`/`println`. Imports heaps of code. Use
console.log
. But even the latter isn’t efficiently implemented. • Prefer
unsafeCast<Foo>()
over
as Foo
when you’re certain of the type. The latter adds overhead and imports more code from stdlib. • Use
external
when possible to reduce amount of classes & interfaces.
K 1
🔥 2
a
Have also run into several of these I wonder if we could create some sort of crowdsourced custom ktlint or detekt ruleset… None of the things you're suggesting against are incorrect enough to be an official IDE warning, but I'd love to be able to learn from others discoveries haha
👍 1
g
crowdsourced custom ktlint or detekt ruleset
at least some should be just a compiler optimization
h
Nice list. I'll look into what effects I can get in my own projects right away!
r
@Marc Knaup have you made your tests with Legacy or IR backend?
m
IR
r
If anyone is interested in some real data. After making some of those changes to the whole KVision code (mostly
toString
and
as
) the large KVision app bundle size changed: - from 3734268 to 3733838 (for legacy compiler) (-0,01%) - from 5322345 to 5319680 (for IR compiler) (-0,05%) 😉 So no miracles here but it does work. And the legacy compiler is better optimized as should be expected.
👍 1
And in KVision I use UglifyJS instead of Terser, so it can have different impact as well.
And by doing these tests I've noticed something else. While with the legacy compiler UglifyJS gives better results than Terser, it's not true for IR anymore. Terser gives slightly better results with IR (about 1%).
m
I’ve saved 10% for my entire website especially by using
external
and
inline
excessively.
IR JS code looks pretty much non-optimized.
Also stripped 10% of page load time according to Lighthouse.
• Avoid
data class
as it will add lots of implementations that you likely never use but that increase bundle size. E.g. if you only need
equals()
you don’t want
hashCode()
,
componentX()
and esp.
toString()
to be generated. Likely cannot be removed by the minimizer.