Skip to content

Instantly share code, notes, and snippets.

@lilac
Last active December 4, 2022 09:13
Show Gist options
  • Save lilac/46edeb55a8a9869238575e9031fb48a0 to your computer and use it in GitHub Desktop.
Save lilac/46edeb55a8a9869238575e9031fb48a0 to your computer and use it in GitHub Desktop.
Embed javascript in JVM

Prerequisites

  1. Install graalvm.
sdk install java 22.3.r19-grl
  1. Change current JVM to graalvm.
sdk use java 22.3.r19-grl
  1. Install Graal js following the guide.
gu install js

Demo

  1. Create sample javascript files. Note that to use javascript modules, the files have to be with mjs suffix.
  • foo.mjs
  • main.mjs
  1. Run the javascript code.
js main.mjs

Benchmark

Let's do a simple benchmark to see how it performs. The benchmark is inspired by this one.

  1. Run fib.js.
time js fib.js
js fib.js  0.32s user 0.06s system 125% cpu 0.303 total
  1. Run fib.py.
time python fib.py
python fib.py  4.34s user 0.03s system 99% cpu 4.409 total

Even for such a simple function, Graal Javascript performs more than 10 times faster than the mature Python interpreter. How amazing it is!.

function fib(n) {
if(n === 0) return 0;
else if(n === 1) return 1;
return fib(n - 2) + fib(n - 1);
}
fib(35);
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
return fib(n - 2) + fib(n - 1)
fib(35)
class Foo {
static square(x) {
return x * x;
}
}
export default Foo
import Foo from './foo.mjs';
// Yes! It supports async & await.
async function f() {
return "hello";
}
console.log(await f());
console.log(Foo.square(3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment