knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

Use C, Rust, Go and Assemblyscript in an R package through WebAssembly

Lifecycle: experimental

The goal of polyglotr is just to show how you can use three different languages through WebAssembly in an R package using wasmr. All of this is very experimental.

Example

library(polyglotr)

The package exposes an inefficient, recursive fibonacci algorithm written in languages that can compile to WebAssembly.

fib_r <- function(n) {
  if (n < 2) return(n)
  fib_r(n - 1) + fib_r(n - 2)
}

As a comparison we also add an rcpp version. In particular it shows what the overhead of opening the wasm file and calling it currently is.

Rcpp::cppFunction("
int fib_rcpp(int n) {
  if (n < 2) return n;
  return fib_rcpp(n - 1) + fib_rcpp(n - 2);
}
")

Each of the following functions calls a bundled binary wasm file in the inst directory that was compiled from the respective language. The binary file is distributed with the package, but not necessarily the source files. The user does not need to compile anything (apart from the wasmr package).

fib_c(20)
fib_rust(20)
fib_assemblyscript(20)
fib_go(20)
fib_r(20)
fib_rcpp(20)

The benchmark is not meant to compare different compilers, just to give a rough feeling about timing. In fact most of the compilers will probably emit very similiar wasm code. The wasm module is read and instantiated upon package load.

I also used tinygo to compile the go code which adds some interface code resulting in a 4kb file. There might be flags to further optimize the generated code.

bench::mark(
  fib_c(20),
  fib_rust(20),
  fib_assemblyscript(20),
  fib_go(20),
  fib_r(20),
  fib_rcpp(20)
)


dirkschumacher/polyglotr documentation built on Nov. 4, 2019, 10:53 a.m.