Running kotlin through JSR-223 is incredibly slow
Asked Answered
P

2

6

I'm running the following code and it's taking between 3 and 6 seconds to execute on both OSX (Sierra) and Windows 10. I've never seen such slowness using JSR-223, especially considering the simplicity of what's being evaluated. Digging through the call tree in YourKit it seems to be spending most of this time in KotlinJsr223JvmLocalScriptEngine.getReplEvaluator, but I can't see past that.

This is using jdk1.8.0_71 and kotlin 1.2.10.

Any ideas?

Thanks

import javax.script.ScriptEngineManager

fun main(args: Array<String>) {
    System.setProperty("idea.io.use.fallback", "true") // need this on windows, not required on osx it seems!
    val engine = ScriptEngineManager().getEngineByExtension("kts")!!

    val startTime = System.currentTimeMillis()

    engine.eval("val x = 5")

    println(System.currentTimeMillis() - startTime)
}

My build script is as follows:

buildscript {
    ext.kotlin_version = '1.2.10'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

group 'xxx'
version '1.0-SNAPSHOT'

apply plugin: 'kotlin'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    compile "org.jetbrains.kotlin:kotlin-script-util:$kotlin_version"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
Potemkin answered 13/2, 2018 at 23:36 Comment(2)
From what I saw, there's some expensive initialization during the first evaluation of an expression, and the consequent calls happen much faster.Onym
I'm running into the same slowness. The first eval does seem like it is longer than later evals, but the later evals are still staggeringly slow, even when the expression is just "1 + 1".Dieselelectric
I
5

I compared kotlin and groovy, both of which are precompiled: engine.compile(script)

Executing kotlin script via jsr223 is one hundred times slower than groovy script.

Irresponsible answered 19/9, 2018 at 7:29 Comment(1)
Is there a sciptEngine for Kotlin in groovy? May you add a ressource, please. I could not find something.Cerumen
M
1

The engine is lazy loaded so you are basically measuring the engine load time. Try doing the following before running your test.

val engine = ScriptEngineManager().getEngineByExtension("kts")
assert(engine.eval("true") as Boolean)

Also you should loop around a few times to get a better measure. Also you can pre-compile to make it faster. Also for real code you can return a lambda so you don't have to evaluate each time.

Manxman answered 1/4, 2020 at 21:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.