rescript-lang / rescript-lang/rescript

Optimizations not applied when record has an optional field

Open
#5,616 16 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
OCaml
Stars
7.5k
Forks
485
Avg merge
1d 2h
Merged PRs (30d)
55

Description

The following code (without an optional field)

type t = {
  a: string,
  b: int
}

let x = { a: "test", b: 1 }
let y = { ...x, b: 5 }

let f = x => { ...x, b: x.b + 1 }

is compiled to

var y = {
  a: "test",
  b: 5
};

function f(x) {
  return {
          a: x.a,
          b: x.b + 1 | 0
        };
}

var x = {
  a: "test",
  b: 1
};

However, as soon as I make a an optional field, the output changes to the more inefficient

var x = {
  a: "test",
  b: 1
};

var newrecord = Caml_obj.obj_dup(x);

newrecord.b = 5;

function f(x) {
  var newrecord = Caml_obj.obj_dup(x);
  newrecord.b = x.b + 1 | 0;
  return newrecord;
}

var y = newrecord;

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the two record-spread examples in the issue and compare the generated JavaScript for required versus optional fields. Trace the compiler's record-update optimization and determine why the optional-field case uses Caml_obj.obj_dup; done means preserving the optimized output where it is valid and adding coverage for both examples.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, ocaml
Domain
compilers, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.