Kotlin Bytecode Generation and Runtime Performance

Kotlin Bytecode Generation

and 

Runtime Performance
Dmitry Jemerov
Dmitry Jemerov, 11-13 May 2016
What is Kotlin
What is Kotlin
What is Kotlin
• Statically typed programming language for JVM, Android and the
browser
• Pragmatic, safe, concise, seamless Java interop
What is Kotlin
• Statically typed programming language for the JVM, Android and
the browser
• Pragmatic, safe, concise, seamless Java interop
Compiling a mixed project
*.java
kotlinc
*.kt
*.class
javac *.class
*.jar
Metadata
@Metadata(

mv = {1, 1, 1},

bv = {1, 0, 0},

k = 1,

d1 = {"u0000"nu0002u0018u0002nu0002u0018u0002nu0002bu0002nu0002u0010bnu0000n
u0002u0010u0002nu0002bu0005nu0002u0018u0002nu0002bu0002bu0017u0018u00002u00020u0001Bu0005¢
u0006u0002u0010u0002Jbu0010u0003u001au00020u0004Hu0007Jbu0010u0005u001au00020u0006Hu0007Jb
u0010u0007u001au00020u0004Hu0007Jbu0010bu001au00020u0004Hu0007J!u0010tu001au0002Hn"u0004b
u0000u0010n2fu0010u000bu001abu0012u0004u0012u0002Hn0fHu0002¢u0006u0002u0010r¨u0006u000e"},

d2 = {"Lorg/jetbrains/LambdaBenchmark;", "Lorg/jetbrains/SizedBenchmark;", "()V", "capturingLambda", "",
"init", "", "mutatingLambda", "noncapturingLambda", "runLambda", "T", "x", "Lkotlin/Function0;", "(Lkotlin/jvm/
functions/Function0;)Ljava/lang/Object;", "production sources for module kotlin-benchmarks"}

)

public class LambdaBenchmark extends SizedBenchmark
{ … }

Working with metadata
class A {

fun foo(): String? = null

fun bar(): String = ""

}



fun main(args: Array<String>) {

println(A::class.functions.filter {

it.returnType.isMarkedNullable

})

}
File-level functions
// Data.kt
fun foo() {

}

public final class DataKt {

public static void foo() {

}

}

@JvmName
@file:JvmName("FooUtils")
fun foo() {

}

public final class FooUtils {

public static final void foo() {

}

}

Primary constructors
class A(val x: Int) {

}

public final class A {

private final int x;



public final int getX() {

return this.x;

}



public A(int x) {

this.x = x;

}

}
Data classes
data class A(val x: Int) {

}

public final class A {
…





public String toString() {

return "A(x=" + this.x + ")";

}



public int hashCode() {

return this.x;

}



public boolean equals(Object o) {
…
}
}

Properties
class A {

var x: String? = null

}

public final class A {

@Nullable

private String x;



@Nullable

public final String getX() {

return this.x;

}



public final void setX(

@Nullable String x) {

this.x = x;

}

}
@JvmField
class A {

@JvmField var x: String? = null

}

public final class A {

@JvmField

@Nullable

public String x;

}
Not-null types
class A {

fun x(s: String) {

println(s)

}
private fun y(s: String) {

println(s)

}

}
public final class A {

public final void x(@NotNull String s) {

Intrinsics.

checkParameterIsNotNull(s, "s");

System.out.println(s);

}



private final void y(String s) {

System.out.println(s);

}

}
Parameter null checks
1 parameter
8 parameters
ns
0 2,25 4,5 6,75 9
Without @NotNull With @NotNull
Extension functions
class A(val i: Int)



fun A.foo(): Int {

return i

}



fun useFoo() {

A(1).foo()

}
public final class ExtFunKt {

public static final void foo(

@NotNull A $receiver) {
return $receiver.getI();

}

}
public static final void useFoo() {

foo(new A(1));

}
Interface methods
interface I {

fun foo(): Int {

return 42

}

}



class C : I {

}
public interface I {

int foo();



public static final class

DefaultImpls {

public static int foo(I $this) {

return 42;

}

}

}

public final class C implements I {

public void foo() {

I.DefaultImpls.foo(this);

}

}
Interface methods: Evolution
interface I {

fun foo(): Int {

return 42

}



fun bar(): Int {

return 239

}

}



// -- separate compilation ——————



class C : I {

}

public interface I {

int foo();
int bar();



public static final class

DefaultImpls { … }

}


// -- separate compilation ——————

public final class C implements I {

public void foo() {

I.DefaultImpls.foo(this);

}

}
Default Arguments
fun foo(x: Int = 42) {
println(x)

}



fun bar() {

foo()

}

public static final void foo(int x) {
System.out.println(x);

}



public static void foo$default(

int x, int mask, …) {


if ((mask & 1) != 0) {

x = 42;

}



foo(x);

}



public static final void bar() {

foo$default(0, 1, …);

}
Default Arguments
1 parameter
8 parameters
ns
0 3,75 7,5 11,25 15
Without default values With default values
@JvmOverloads
@JvmOverloads

fun foo(x: Int = 42) {

}

public static final void foo(int x)
{

}



public static void foo$default(

int x, int mask, …) { … }



public static void foo() {

foo$default(0, 1, …);

}
Lambdas: Functional types
fun <T> runLambda(x: () -> T): T =
x()

private static final
Object runLambda(Function0 x) {

return x.invoke();

}

package kotlin.jvm.functions



/** A function that takes 0 arguments. */

public interface Function0<out R> : Function<R> {

/** Invokes the function. */

public operator fun invoke(): R

}
Lambdas: Noncapturing
var value = 0



fun noncapLambda(): Int 

= runLambda { value }

final class LB$noncapLambda$1 

extends Lambda implements Function0 {



public static final LB$noncapLambda$1 

INSTANCE = new LB$noncapLambda$1();



public final int invoke() {

return LambdaBenchmarkKt.getValue();

}

}
public static int noncapLambda() {

return ((Number)runLambda(

LB$noncapLambda$1.INSTANCE)
).intValue();

}
Lambdas: Capturing
fun capturingLambda(v: Int): Int

= runLambda { v }
public static int

capturingLambda(int value) {

return ((Number)RL.runLambda(

new Function0(0) {

public final int invoke() {

return value;

}

})
).intValue();

Lambdas: Capture and mutate
fun mutatingLambda(): Int {

var x = 0

runLambda { x++ }

return x

}

public static int mutatingLambda()
{

final IntRef x = new IntRef();

x.element = 0;

RL.runLambda(new Function0(0) {

public final int invoke() {

int var1 = x.element++;

return var1;

}

});

return x.element;

}

public static final class IntRef {

public volatile int element;



@Override

public String toString() {

return String.valueOf(element);

}

}
Lambdas
Noncapturing
Capturing
Mutating
ns
0 45 90 135 180
Java Kotlin
Lambdas: inline
fun inlineLambda(x: Int): Int =

run { x }

public static int
inlineLambda(int x) {

return x;

}

/**

* Calls the specified function [block] and returns its result.

*/

public inline fun <R> run(block: () -> R): R = block()
Method References
private fun referenced() = 1



fun runReference() {

runLambda(::referenced)

}

final class MethodReferenceKt$runReference$1 

extends FunctionReference implements Function0
{



public static final MethodReferenceKt
$runReference$1 INSTANCE = new
MethodReferenceKt$runReference$1();



public final int invoke() {

return MethodReferenceKt.access
$referenced();

}



public final KDeclarationContainer 

getOwner() { … }



public final String getName() { … }



public final String getSignature() { … }

}
Loops: Range
fun rangeLoop() {

for (i in 1..10) {

println(i)

}

}

public static final void
rangeLoop() {

int i = 1;

byte var1 = 10;

if(i <= var1) {

while(true) {

System.out.println(i);

if(i == var1) {

break;

}



++i;

}

}

}
Loops: Array
fun arrayLoop(x: Array<String>) {

for (s in x) {

println(s)

}

}
public static void
arrayLoop(@NotNull String[] x) {

for(int var2 = 0; 

var2 < x.length; ++var2) {

String s = x[var2];

System.out.println(s);

}

}

Loops: List
fun listLoop(x: List<String>) {

for (s in x) {

println(s)

}

}
public static final void
listLoop(@NotNull List x) {


Iterator var2 = x.iterator();



while(var2.hasNext()) {

String s =

(String)var2.next();

System.out.println(s);

}

}
Loops
Range
Array
ArrayList
ns
0 27,5 55 82,5 110
Java Kotlin
When: Table lookup
fun tableWhen(x: Int): String =
when(x) {

0 -> "zero"

1 -> "one"

else -> "many"

}
public static String tableWhen(int x)
{
String var10000;

switch(x) {

case 0:

var10000 = "zero";

break;

case 1:

var10000 = "one";

break;

default:

var10000 = "many";

}



return var10000;

}
When: Constants
val ZERO = 0

val ONE = 1



fun constWhen(x: Int): String =
when(x) {

ZERO -> "zero"

ONE -> "one"

else -> "many"

}
public static String constWhen(

int x) {

return x == ZERO ? “zero"
: (x == ONE ? “one" : "many");

}

When: enum
enum class NumberValue {
ZERO, ONE, MANY
}



fun enumWhen(x: NumberValue):
String = when(x) {

NumberValue.ZERO -> "zero"

NumberValue.ONE -> "one"

else -> "many"

}
public static String
enumWhen(@NotNull NumberValue x) {

String var10000;

switch(WhenEnumKt$WhenMappings.
$EnumSwitchMapping$0[x.ordinal()]) {

case 1:

var10000 = "zero";

break;

case 2:

var10000 = "one";

break;

default:

var10000 = "many";

}

return var10000;

}
When
Lookup
Compare
Enum
ns
0 5,5 11 16,5 22
Java Kotlin
Summary
• Kotlin allows writing code which is easy to use from Java
• Performance in most scenarios is on par with Java
• Inline functions 👍
• Measure the performance of your code, not micro-examples
https://www.manning.com/books/kotlin-in-action
Q&A
yole@jetbrains.com
@intelliyole
1 of 40

Recommended

Idiomatic Kotlin by
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
7.4K views56 slides
Building secure applications with keycloak by
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak Abhishek Koserwal
7.9K views20 slides
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter... by
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
184.2K views99 slides
Protocol Buffers by
Protocol BuffersProtocol Buffers
Protocol BuffersKnoldus Inc.
1.3K views19 slides
Real Life Clean Architecture by
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean ArchitectureMattia Battiston
36.6K views80 slides
Utilizing kotlin flows in an android application by
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationSeven Peaks Speaks
220 views63 slides

More Related Content

What's hot

In-depth analysis of Kotlin Flows by
In-depth analysis of Kotlin FlowsIn-depth analysis of Kotlin Flows
In-depth analysis of Kotlin FlowsGlobalLogic Ukraine
303 views131 slides
Gradle Introduction by
Gradle IntroductionGradle Introduction
Gradle IntroductionDmitry Buzdin
7.8K views39 slides
Java 8 Workshop by
Java 8 WorkshopJava 8 Workshop
Java 8 WorkshopMario Fusco
7.4K views85 slides
Idiomatic kotlin by
Idiomatic kotlinIdiomatic kotlin
Idiomatic kotlinAnton Arhipov
177 views109 slides
Spring Boot—Production Boost by
Spring Boot—Production BoostSpring Boot—Production Boost
Spring Boot—Production BoostVMware Tanzu
661 views21 slides
Deep dive into Coroutines on JVM @ KotlinConf 2017 by
Deep dive into Coroutines on JVM @ KotlinConf 2017Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Roman Elizarov
5.8K views107 slides

What's hot(20)

Java 8 Workshop by Mario Fusco
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco7.4K views
Spring Boot—Production Boost by VMware Tanzu
Spring Boot—Production BoostSpring Boot—Production Boost
Spring Boot—Production Boost
VMware Tanzu661 views
Deep dive into Coroutines on JVM @ KotlinConf 2017 by Roman Elizarov
Deep dive into Coroutines on JVM @ KotlinConf 2017Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017
Roman Elizarov5.8K views
[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang) by Johnny Sung
[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang) [Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang)
[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang)
Johnny Sung902 views
Spring Framework Petclinic sample application by Antoine Rey
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
Antoine Rey31.8K views
Scalability, Availability & Stability Patterns by Jonas Bonér
Scalability, Availability & Stability PatternsScalability, Availability & Stability Patterns
Scalability, Availability & Stability Patterns
Jonas Bonér516K views
Docker Networking - Common Issues and Troubleshooting Techniques by Sreenivas Makam
Docker Networking - Common Issues and Troubleshooting TechniquesDocker Networking - Common Issues and Troubleshooting Techniques
Docker Networking - Common Issues and Troubleshooting Techniques
Sreenivas Makam42.6K views
Core Java Slides by Vinit Vyas
Core Java SlidesCore Java Slides
Core Java Slides
Vinit Vyas22.9K views
A Brief Intro to Scala by Tim Underwood
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
Tim Underwood23.1K views
Monadic Java by Mario Fusco
Monadic JavaMonadic Java
Monadic Java
Mario Fusco65.9K views
Being Functional on Reactive Streams with Spring Reactor by Max Huang
Being Functional on Reactive Streams with Spring ReactorBeing Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring Reactor
Max Huang296 views
Apache Kafka - Event Sourcing, Monitoring, Librdkafka, Scaling & Partitioning by Guido Schmutz
Apache Kafka - Event Sourcing, Monitoring, Librdkafka, Scaling & PartitioningApache Kafka - Event Sourcing, Monitoring, Librdkafka, Scaling & Partitioning
Apache Kafka - Event Sourcing, Monitoring, Librdkafka, Scaling & Partitioning
Guido Schmutz1.6K views
Intro to Asynchronous Javascript by Garrett Welson
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson602 views

Similar to Kotlin Bytecode Generation and Runtime Performance

Kotlin decompiled by
Kotlin decompiledKotlin decompiled
Kotlin decompiledRuslan Klymenko
144 views89 slides
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015 by
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Codemotion
2.6K views66 slides
Apache Flink Training: DataStream API Part 2 Advanced by
Apache Flink Training: DataStream API Part 2 Advanced Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced Flink Forward
9.6K views37 slides
Hw09 Hadoop + Clojure by
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + ClojureCloudera, Inc.
1.3K views21 slides
Kotlin for Android Developers - 3 by
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
310 views132 slides
Introduction to kotlin + spring boot demo by
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
113 views78 slides

Similar to Kotlin Bytecode Generation and Runtime Performance(20)

Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015 by Codemotion
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Codemotion2.6K views
Apache Flink Training: DataStream API Part 2 Advanced by Flink Forward
Apache Flink Training: DataStream API Part 2 Advanced Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced
Flink Forward9.6K views
Introduction to kotlin + spring boot demo by Muhammad Abdullah
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
Muhammad Abdullah113 views
TI1220 Lecture 6: First-class Functions by Eelco Visser
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser1.1K views
Nice to meet Kotlin by Jieyi Wu
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
Jieyi Wu170 views
The... Wonderful? World of Lambdas by Esther Lozano
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
Esther Lozano504 views
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016 by STX Next
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next820 views
Kotlin Developer Starter in Android projects by Bartosz Kosarzycki
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki5.1K views
JavaOne 2016 - Learn Lambda and functional programming by Henri Tremblay
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
Henri Tremblay377 views
Kotlin Perfomance on Android / Александр Смирнов (Splyt) by Ontico
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Ontico349 views
C# 6.0 - April 2014 preview by Paulo Morgado
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
Paulo Morgado3K views
Functional Programming You Already Know by Kevlin Henney
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already Know
Kevlin Henney1.4K views
Lies Told By The Kotlin Compiler by Garth Gilmour
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
Garth Gilmour7 views

More from intelliyole

Kotlin: Why Do You Care? by
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?intelliyole
5.4K views67 slides
Feel of Kotlin (Berlin JUG 16 Apr 2015) by
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)intelliyole
1.4K views85 slides
From Renamer Plugin to Polyglot IDE by
From Renamer Plugin to Polyglot IDEFrom Renamer Plugin to Polyglot IDE
From Renamer Plugin to Polyglot IDEintelliyole
5.3K views80 slides
How to Build Developer Tools on Top of IntelliJ Platform by
How to Build Developer Tools on Top of IntelliJ PlatformHow to Build Developer Tools on Top of IntelliJ Platform
How to Build Developer Tools on Top of IntelliJ Platformintelliyole
7.8K views41 slides
The Kotlin Programming Language by
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
9.4K views52 slides
IntelliJ IDEA: Life after Open Source by
IntelliJ IDEA: Life after Open SourceIntelliJ IDEA: Life after Open Source
IntelliJ IDEA: Life after Open Sourceintelliyole
3.1K views28 slides

More from intelliyole(9)

Kotlin: Why Do You Care? by intelliyole
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
intelliyole5.4K views
Feel of Kotlin (Berlin JUG 16 Apr 2015) by intelliyole
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
intelliyole1.4K views
From Renamer Plugin to Polyglot IDE by intelliyole
From Renamer Plugin to Polyglot IDEFrom Renamer Plugin to Polyglot IDE
From Renamer Plugin to Polyglot IDE
intelliyole5.3K views
How to Build Developer Tools on Top of IntelliJ Platform by intelliyole
How to Build Developer Tools on Top of IntelliJ PlatformHow to Build Developer Tools on Top of IntelliJ Platform
How to Build Developer Tools on Top of IntelliJ Platform
intelliyole7.8K views
The Kotlin Programming Language by intelliyole
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
intelliyole9.4K views
IntelliJ IDEA: Life after Open Source by intelliyole
IntelliJ IDEA: Life after Open SourceIntelliJ IDEA: Life after Open Source
IntelliJ IDEA: Life after Open Source
intelliyole3.1K views
Smoothing Your Java with DSLs by intelliyole
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole1.1K views
Implementing Refactorings in IntelliJ IDEA by intelliyole
Implementing Refactorings in IntelliJ IDEAImplementing Refactorings in IntelliJ IDEA
Implementing Refactorings in IntelliJ IDEA
intelliyole2.9K views
IntelliJ IDEA Architecture and Performance by intelliyole
IntelliJ IDEA Architecture and PerformanceIntelliJ IDEA Architecture and Performance
IntelliJ IDEA Architecture and Performance
intelliyole9.2K views

Recently uploaded

Short_Story_PPT.pdf by
Short_Story_PPT.pdfShort_Story_PPT.pdf
Short_Story_PPT.pdfutkarshsatishkumarsh
5 views16 slides
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Donato Onofri
860 views34 slides
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Lisi Hocke
35 views124 slides
ShortStory_qlora.pptx by
ShortStory_qlora.pptxShortStory_qlora.pptx
ShortStory_qlora.pptxpranathikrishna22
5 views10 slides
Quality Engineer: A Day in the Life by
Quality Engineer: A Day in the LifeQuality Engineer: A Day in the Life
Quality Engineer: A Day in the LifeJohn Valentino
6 views18 slides
Generic or specific? Making sensible software design decisions by
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
6 views60 slides

Recently uploaded(20)

Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by Donato Onofri
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Donato Onofri860 views
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 views
Quality Engineer: A Day in the Life by John Valentino
Quality Engineer: A Day in the LifeQuality Engineer: A Day in the Life
Quality Engineer: A Day in the Life
John Valentino6 views
Generic or specific? Making sensible software design decisions by Bert Jan Schrijver
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm15 views
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports by Ra'Fat Al-Msie'deen
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsBushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
FOSSLight Community Day 2023-11-30 by Shane Coughlan
FOSSLight Community Day 2023-11-30FOSSLight Community Day 2023-11-30
FOSSLight Community Day 2023-11-30
Shane Coughlan5 views
tecnologia18.docx by nosi6702
tecnologia18.docxtecnologia18.docx
tecnologia18.docx
nosi67025 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated... by TomHalpin9
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
TomHalpin96 views

Kotlin Bytecode Generation and Runtime Performance

  • 1. Kotlin Bytecode Generation
 and 
 Runtime Performance Dmitry Jemerov Dmitry Jemerov, 11-13 May 2016
  • 4. What is Kotlin • Statically typed programming language for JVM, Android and the browser • Pragmatic, safe, concise, seamless Java interop
  • 5. What is Kotlin • Statically typed programming language for the JVM, Android and the browser • Pragmatic, safe, concise, seamless Java interop
  • 6. Compiling a mixed project *.java kotlinc *.kt *.class javac *.class *.jar
  • 7. Metadata @Metadata(
 mv = {1, 1, 1},
 bv = {1, 0, 0},
 k = 1,
 d1 = {"u0000"nu0002u0018u0002nu0002u0018u0002nu0002bu0002nu0002u0010bnu0000n u0002u0010u0002nu0002bu0005nu0002u0018u0002nu0002bu0002bu0017u0018u00002u00020u0001Bu0005¢ u0006u0002u0010u0002Jbu0010u0003u001au00020u0004Hu0007Jbu0010u0005u001au00020u0006Hu0007Jb u0010u0007u001au00020u0004Hu0007Jbu0010bu001au00020u0004Hu0007J!u0010tu001au0002Hn"u0004b u0000u0010n2fu0010u000bu001abu0012u0004u0012u0002Hn0fHu0002¢u0006u0002u0010r¨u0006u000e"},
 d2 = {"Lorg/jetbrains/LambdaBenchmark;", "Lorg/jetbrains/SizedBenchmark;", "()V", "capturingLambda", "", "init", "", "mutatingLambda", "noncapturingLambda", "runLambda", "T", "x", "Lkotlin/Function0;", "(Lkotlin/jvm/ functions/Function0;)Ljava/lang/Object;", "production sources for module kotlin-benchmarks"}
 )
 public class LambdaBenchmark extends SizedBenchmark { … }

  • 8. Working with metadata class A {
 fun foo(): String? = null
 fun bar(): String = ""
 }
 
 fun main(args: Array<String>) {
 println(A::class.functions.filter {
 it.returnType.isMarkedNullable
 })
 }
  • 9. File-level functions // Data.kt fun foo() {
 }
 public final class DataKt {
 public static void foo() {
 }
 }

  • 10. @JvmName @file:JvmName("FooUtils") fun foo() {
 }
 public final class FooUtils {
 public static final void foo() {
 }
 }

  • 11. Primary constructors class A(val x: Int) {
 }
 public final class A {
 private final int x;
 
 public final int getX() {
 return this.x;
 }
 
 public A(int x) {
 this.x = x;
 }
 }
  • 12. Data classes data class A(val x: Int) {
 }
 public final class A { …
 
 
 public String toString() {
 return "A(x=" + this.x + ")";
 }
 
 public int hashCode() {
 return this.x;
 }
 
 public boolean equals(Object o) { … } }

  • 13. Properties class A {
 var x: String? = null
 }
 public final class A {
 @Nullable
 private String x;
 
 @Nullable
 public final String getX() {
 return this.x;
 }
 
 public final void setX(
 @Nullable String x) {
 this.x = x;
 }
 }
  • 14. @JvmField class A {
 @JvmField var x: String? = null
 }
 public final class A {
 @JvmField
 @Nullable
 public String x;
 }
  • 15. Not-null types class A {
 fun x(s: String) {
 println(s)
 } private fun y(s: String) {
 println(s)
 }
 } public final class A {
 public final void x(@NotNull String s) {
 Intrinsics.
 checkParameterIsNotNull(s, "s");
 System.out.println(s);
 }
 
 private final void y(String s) {
 System.out.println(s);
 }
 }
  • 16. Parameter null checks 1 parameter 8 parameters ns 0 2,25 4,5 6,75 9 Without @NotNull With @NotNull
  • 17. Extension functions class A(val i: Int)
 
 fun A.foo(): Int {
 return i
 }
 
 fun useFoo() {
 A(1).foo()
 } public final class ExtFunKt {
 public static final void foo(
 @NotNull A $receiver) { return $receiver.getI();
 }
 } public static final void useFoo() {
 foo(new A(1));
 }
  • 18. Interface methods interface I {
 fun foo(): Int {
 return 42
 }
 }
 
 class C : I {
 } public interface I {
 int foo();
 
 public static final class
 DefaultImpls {
 public static int foo(I $this) {
 return 42;
 }
 }
 }
 public final class C implements I {
 public void foo() {
 I.DefaultImpls.foo(this);
 }
 }
  • 19. Interface methods: Evolution interface I {
 fun foo(): Int {
 return 42
 }
 
 fun bar(): Int {
 return 239
 }
 }
 
 // -- separate compilation ——————
 
 class C : I {
 }
 public interface I {
 int foo(); int bar();
 
 public static final class
 DefaultImpls { … }
 } 
 // -- separate compilation ——————
 public final class C implements I {
 public void foo() {
 I.DefaultImpls.foo(this);
 }
 }
  • 20. Default Arguments fun foo(x: Int = 42) { println(x)
 }
 
 fun bar() {
 foo()
 }
 public static final void foo(int x) { System.out.println(x);
 }
 
 public static void foo$default(
 int x, int mask, …) { 
 if ((mask & 1) != 0) {
 x = 42;
 }
 
 foo(x);
 }
 
 public static final void bar() {
 foo$default(0, 1, …);
 }
  • 21. Default Arguments 1 parameter 8 parameters ns 0 3,75 7,5 11,25 15 Without default values With default values
  • 22. @JvmOverloads @JvmOverloads
 fun foo(x: Int = 42) {
 }
 public static final void foo(int x) {
 }
 
 public static void foo$default(
 int x, int mask, …) { … }
 
 public static void foo() {
 foo$default(0, 1, …);
 }
  • 23. Lambdas: Functional types fun <T> runLambda(x: () -> T): T = x()
 private static final Object runLambda(Function0 x) {
 return x.invoke();
 }
 package kotlin.jvm.functions
 
 /** A function that takes 0 arguments. */
 public interface Function0<out R> : Function<R> {
 /** Invokes the function. */
 public operator fun invoke(): R
 }
  • 24. Lambdas: Noncapturing var value = 0
 
 fun noncapLambda(): Int 
 = runLambda { value }
 final class LB$noncapLambda$1 
 extends Lambda implements Function0 {
 
 public static final LB$noncapLambda$1 
 INSTANCE = new LB$noncapLambda$1();
 
 public final int invoke() {
 return LambdaBenchmarkKt.getValue();
 }
 } public static int noncapLambda() {
 return ((Number)runLambda(
 LB$noncapLambda$1.INSTANCE) ).intValue();
 }
  • 25. Lambdas: Capturing fun capturingLambda(v: Int): Int
 = runLambda { v } public static int
 capturingLambda(int value) {
 return ((Number)RL.runLambda(
 new Function0(0) {
 public final int invoke() {
 return value;
 }
 }) ).intValue();

  • 26. Lambdas: Capture and mutate fun mutatingLambda(): Int {
 var x = 0
 runLambda { x++ }
 return x
 }
 public static int mutatingLambda() {
 final IntRef x = new IntRef();
 x.element = 0;
 RL.runLambda(new Function0(0) {
 public final int invoke() {
 int var1 = x.element++;
 return var1;
 }
 });
 return x.element;
 }
 public static final class IntRef {
 public volatile int element;
 
 @Override
 public String toString() {
 return String.valueOf(element);
 }
 }
  • 28. Lambdas: inline fun inlineLambda(x: Int): Int =
 run { x }
 public static int inlineLambda(int x) {
 return x;
 }
 /**
 * Calls the specified function [block] and returns its result.
 */
 public inline fun <R> run(block: () -> R): R = block()
  • 29. Method References private fun referenced() = 1
 
 fun runReference() {
 runLambda(::referenced)
 }
 final class MethodReferenceKt$runReference$1 
 extends FunctionReference implements Function0 {
 
 public static final MethodReferenceKt $runReference$1 INSTANCE = new MethodReferenceKt$runReference$1();
 
 public final int invoke() {
 return MethodReferenceKt.access $referenced();
 }
 
 public final KDeclarationContainer 
 getOwner() { … }
 
 public final String getName() { … }
 
 public final String getSignature() { … }
 }
  • 30. Loops: Range fun rangeLoop() {
 for (i in 1..10) {
 println(i)
 }
 }
 public static final void rangeLoop() {
 int i = 1;
 byte var1 = 10;
 if(i <= var1) {
 while(true) {
 System.out.println(i);
 if(i == var1) {
 break;
 }
 
 ++i;
 }
 }
 }
  • 31. Loops: Array fun arrayLoop(x: Array<String>) {
 for (s in x) {
 println(s)
 }
 } public static void arrayLoop(@NotNull String[] x) {
 for(int var2 = 0; 
 var2 < x.length; ++var2) {
 String s = x[var2];
 System.out.println(s);
 }
 }

  • 32. Loops: List fun listLoop(x: List<String>) {
 for (s in x) {
 println(s)
 }
 } public static final void listLoop(@NotNull List x) { 
 Iterator var2 = x.iterator();
 
 while(var2.hasNext()) {
 String s =
 (String)var2.next();
 System.out.println(s);
 }
 }
  • 34. When: Table lookup fun tableWhen(x: Int): String = when(x) {
 0 -> "zero"
 1 -> "one"
 else -> "many"
 } public static String tableWhen(int x) { String var10000;
 switch(x) {
 case 0:
 var10000 = "zero";
 break;
 case 1:
 var10000 = "one";
 break;
 default:
 var10000 = "many";
 }
 
 return var10000;
 }
  • 35. When: Constants val ZERO = 0
 val ONE = 1
 
 fun constWhen(x: Int): String = when(x) {
 ZERO -> "zero"
 ONE -> "one"
 else -> "many"
 } public static String constWhen(
 int x) {
 return x == ZERO ? “zero" : (x == ONE ? “one" : "many");
 }

  • 36. When: enum enum class NumberValue { ZERO, ONE, MANY }
 
 fun enumWhen(x: NumberValue): String = when(x) {
 NumberValue.ZERO -> "zero"
 NumberValue.ONE -> "one"
 else -> "many"
 } public static String enumWhen(@NotNull NumberValue x) {
 String var10000;
 switch(WhenEnumKt$WhenMappings. $EnumSwitchMapping$0[x.ordinal()]) {
 case 1:
 var10000 = "zero";
 break;
 case 2:
 var10000 = "one";
 break;
 default:
 var10000 = "many";
 }
 return var10000;
 }
  • 38. Summary • Kotlin allows writing code which is easy to use from Java • Performance in most scenarios is on par with Java • Inline functions 👍 • Measure the performance of your code, not micro-examples