parseAttribute: every plain-text attribute throws inside isJSON, which is slow when rendering on the server

オープン 初心者向け
#201 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
72/100
issue の種類
リファクタリング
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
javascript, node.js
領域
performance

調査の方向性

作業対象は parseAttribute と、その補助関数 isJSON です。isJSON は各値に対して try/catch の中で JSON.parse を呼び出します。もう一つは isNumber で、呼び出しのたびに RegExp を作り直しています。まずこの3つの関数と、parseAttribute をカバーしている既存のテストを読んでください。完了条件は、JSON ではない値が例外を投げずに返ること、JSON の値が一度だけ解析されること、そして既存のテストが変更なしで通ることです。

索引モデルが issue の本文から書いたものです。

説明

Goal

Reading an attribute that is plain text (a class, a label, an address) costs no thrown exception, on the server as in the browser.

Context

parseAttribute asks isJSON(value) first, and isJSON is try { return JSON.parse(value) && !!value } catch { return false }. Most attribute values are plain text, so most calls throw: the engine builds a SyntaxError with its stack each time, and a value that is JSON is parsed twice, once to test and once to read. isNumber builds its RegExp anew on every call as well.

In the browser this runs once per element at upgrade and nobody notices. With element-js-ssr-renderer it runs for every attribute of every instance on every request, deep inside the recursion of the render, where a stack is long. In a CPU profile of a form page with a few dozen elements parseAttribute was the largest single function, about a seventh of the whole request. On a runtime that limits CPU per request (Cloudflare Workers) that decides whether a page fits.

Acceptance criteria

  • A value that cannot be JSON is returned without an exception being thrown
  • A value that is JSON is parsed once
  • parseAttribute returns for every value what it returns today; the existing tests pass unchanged

Proposal (non-binding)

Look at the value before parsing it: true, false and null by comparison; JSON.parse only where the first character can open JSON ({, [, ", -, a digit), with its result kept instead of parsed again; the number pattern as a constant.

Out of scope

  • What a boolean attribute without a value reads as (#199)
主要言語
JavaScript
スター
30
フォーク
5
平均マージ
1時間 57分
マージ済み PR(30日)
10

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

webtides/element-js のほかの issue

webtides/element-js の issue をすべて見る

似ている issue

JavaScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。