Class vs Function Constructor

Нашел отличную статью в блоге v8 о классах и быстрой инициализацией полей классов (апрель 2022). Захотелось проверить это на деле.

Как входной параметр возьмем код, написанный в 2-х стилях: функция конструктор и класс

`const Status = Object.freeze({ OK: "OK", ERROR: "ERROR", });

function unwrap() { if (this.status === Status.OK) { return this.data; } else { throw new Error("Unwrap called on an error"); } } function ResultCtorFn(dataOrError, status) { this.status = status; if (status === Status.OK) { this.data = dataOrError; } else { this.error = dataOrError; } this.unwrap = unwrap.bind(this); } ResultCtorFn.prototype.Ok = function (value) { return ResultCtorFn(value, Status.OK); };

ResultCtorFn.prototype.Err = function (value) { return ResultCtorFn(value, Status.ERROR); };

class ResultCls { constructor(dataOrError, status) { if (status === Status.OK) { this.data = dataOrError; } else { this.error = dataOrError; } this.status = status; }

unwrap() { if (this.status === Status.OK) { return this.data; } else { throw new Error("Unwrap called on an error"); } }

static Ok(value) { return new ResultCls(value, Status.OK); }

static Err(value) { return new ResultCls(value, Status.ERROR); } }

function main() { const fnCtorRes = new ResultCtorFn("qwe, new fn", Status.OK); const clsRes = new ResultCls("qwe, class", Status.OK);

console.log("qwe, new fn", fnCtorRes.unwrap()); console.log("qwe, class", clsRes.unwrap()); } main();

замеряем с помощью следующей команды `node --print-bytecode --print-opt-code --print-code ./src/index.js > index.bytecode.txt

и смотрим с помощью поиска 2 функции: ResultCtorFn и ResultCls. Обратите внимание, что стиль создания инстансов одинаковый.

ResultCls (class) `Bytecode length: 38 Parameter count 3 Register count 2 Frame size 16

и ResultCtorFn (function constructor) `Bytecode length: 53 Parameter count 3 Register count 3 Frame size 24

Классы более оптимально упакованы, по сравнению с функцией конструктором (node.js v22.14.0). Это значит, что лучше в v8 использовать классы. А вы знали этот факт? Делитесь в коментарии.

#v8 #performance #js #javascript #tip_of_the_day @haradkou_sdet````