Skip to content

Optimise comparison with singleton custom types on JavaScript #4903

@GearsDatapacks

Description

@GearsDatapacks

Currently, if you have some code like this:

pub type Wibble {
  Wibble
  Wobble
}

pub fn is_wibble(w: Wibble) -> Bool {
  w == Wibble
}

On the JavaScript target, this code is generated for the is_wibble function:

export function is_wibble(w) {
  return isEqual(w, new Wibble());
}

This works, but it's very slow. It needs to construct a new Wibble, and then call the isEqual function, which supports any shape of data, and so does a lot of extra logic which isn't necessary.

For the case when we're comparing to a "singleton" custom type, i.e. one with no fields, we could instead generate this:

export function is_wibble(w) {
  return w instanceof Wibble;
}

This is what we generate for pattern matching. With some basic benchmarks, it seems this is over 10x faster:

Input               Function                       IPS           Min           P99
100k elements       equality                   40.0693       23.9345       27.1689
100k elements       instanceof                523.1122        1.5164        4.1579

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions