SlideShare a Scribd company logo
1 of 40
Download to read offline
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

More Related Content

What's hot

What's hot (20)

Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Lazy java
Lazy javaLazy java
Lazy java
 
Boost your productivity with Scala tooling!
Boost your productivity  with Scala tooling!Boost your productivity  with Scala tooling!
Boost your productivity with Scala tooling!
 
Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Bytecode Manipulation with a Java Agent and Byte Buddy
Bytecode Manipulation with a Java Agent and Byte BuddyBytecode Manipulation with a Java Agent and Byte Buddy
Bytecode Manipulation with a Java Agent and Byte Buddy
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Kotlin coroutine - behind the scenes
Kotlin coroutine - behind the scenesKotlin coroutine - behind the scenes
Kotlin coroutine - behind the scenes
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!
 
Intro to kotlin
Intro to kotlinIntro to kotlin
Intro to kotlin
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
 
LatJUG. Java Bytecode Fundamentals
LatJUG. Java Bytecode FundamentalsLatJUG. Java Bytecode Fundamentals
LatJUG. Java Bytecode Fundamentals
 
Java Quiz Questions
Java Quiz QuestionsJava Quiz Questions
Java Quiz Questions
 
Intégration continue et déploiement continue avec Jenkins
Intégration continue et déploiement continue avec JenkinsIntégration continue et déploiement continue avec Jenkins
Intégration continue et déploiement continue avec Jenkins
 
Idiomatic kotlin
Idiomatic kotlinIdiomatic kotlin
Idiomatic kotlin
 

Similar to Kotlin Bytecode Generation and Runtime Performance

Apache Flink Training: DataStream API Part 2 Advanced
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
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
Paulo Morgado
 

Similar to Kotlin Bytecode Generation and Runtime Performance (20)

Kotlin decompiled
Kotlin decompiledKotlin decompiled
Kotlin decompiled
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
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
 
Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
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
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functions
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
 
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already Know
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 

More from 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)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
intelliyole
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
intelliyole
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 

More from intelliyole (9)

Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
 
From Renamer Plugin to Polyglot IDE
From Renamer Plugin to Polyglot IDEFrom Renamer Plugin to Polyglot IDE
From Renamer Plugin to Polyglot IDE
 
How to Build Developer Tools on Top of IntelliJ Platform
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
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
IntelliJ IDEA: Life after Open Source
IntelliJ IDEA: Life after Open SourceIntelliJ IDEA: Life after Open Source
IntelliJ IDEA: Life after Open Source
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Implementing Refactorings in IntelliJ IDEA
Implementing Refactorings in IntelliJ IDEAImplementing Refactorings in IntelliJ IDEA
Implementing Refactorings in IntelliJ IDEA
 
IntelliJ IDEA Architecture and Performance
IntelliJ IDEA Architecture and PerformanceIntelliJ IDEA Architecture and Performance
IntelliJ IDEA Architecture and Performance
 

Recently uploaded

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Recently uploaded (20)

Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

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