• Stars
    star
    197
  • Rank 197,722 (Top 4 %)
  • Language
    HTML
  • License
    Other
  • Created over 6 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Proposal for a programmable JS profiling API for collecting JS profiles from real end-user environments

JavaScript Self-Profiling API Proposal

Motivation

Currently it is difficult for web developers to understand how their applications perform in the wide variety of conditions encountered on real user devices. A programmable JS profiling API is needed to collect JS profiles from real end-user environments.

A native self-profiling API for JS code would also allow web developers to efficiently find hotspots in their JS code during page loads and user interactions, to assign CPU budgets to individual JS-implemented features on the page, to find unnecessary work being done on the client, and to find low-priority JS code executing in the background and wasting device power.

Currently JS self-profiling can be accomplished by instrumenting individual JS functions with timing code but this is cumbersome, bloats JS size, changes the code (potentially altering performance characteristics), adds overhead from timing calls, and risks missing out on hotspots in unexpected corners.

Facebook's Profiler Polyfill

In an attempt to polyfill the missing self-profiling functionality, Facebook built and deployed its own in-page JS profiler implemented with JavaScript and SharedArrayBuffers. This JS profiler was implemented using a worker thread that signaled to the main thread when it needed to record its current stack. The worker thread would toggle a “capture stack now” flag in a SharedArrayBuffer every few milliseconds, and the value of this flag was read by instrumentation code that was inserted at transpilation time into the beginning of interesting JS functions running on the main thread. If the instrumentation code saw that the flag was set, it would capture the current JS stack (using the Error object) and add it to the running profile.

This JS profiler was enabled for only a small percentage of Facebook users, and only instrumented functions of 10 statements or more in order to limit performance impact and to limit the quantity of profiling data collected. Nevertheless, we found it extremely valuable for understanding Facebook.com's performance in the field and for finding optimization opportunities.

This polyfill implementation had some downsides:

  • The size overhead of the added instrumentation required limiting the fraction of functions instrumented (resulting in incomplete coverage)
  • The sampling “interrupt” was not instant so stacks were collected from the next instrumented function which added a lot of noise to the dataset and made it difficult to reason about
  • The performance overhead limited the sampling frequency and fraction of pageloads profiled
  • Our design depended on SharedArrayBuffers, which have been disabled on the Web for the time-being, so the profiler is disabled for now

A browser-implemented profiling API would avoid these downsides.

Wider Industry Interest

It is cumbersome to manage instrumentation for performance measurement, regardless of whether it is inserted by build-time tooling (like Facebook's polyfill above) or inserted by hand in functions of interest. This API eliminates the need to maintain performance instrumentation and therefore allows smaller sites to deploy in-page JS profiling.

We also expect that third-party analytics providers will offer libraries or infrastructure to record, ingest, aggregate and automatically analyze the collected profiles for optimization opportunities, thus further lowering the barrier to entry.

Finally, several other Web properties with large codebases have expressed interest to us for using this API to better monitor their webapps performance in the field.

API Overview

Before developers can make use of the profiler, they'll first have to signal to the UA that they wish to profile by exposing the Document-Policy: js-profiling header.

This header ensures that any UA-specific profiling overhead is incurred only on loads that may profile.

Developers will then be able to spin up a new profiler via new Profiler(options), where options contains the following required fields:

  • sampleInterval: Target sample rate (in ms per sample)
    • The UA may choose a different sample rate than the one that the user requested (which must be the next lowest valid sampling interval).
      • The true sample rate of the profiler may be accessible via profiler.sampleInterval.
  • maxBufferSize: Maximum sample capacity (in samples)
    • If the sample buffer capacity is reached, the samplebufferfull event is sent to the profiler object. This stops profiling immediately.
      • The trace may still be collected via profiler.stop() when this occurs.

Creating a new profiler starts profiling immediately. Once the developer wishes to stop profiling, calling profiler.stop() returns a promise containing a trace object that can be sent to a server for aggregation.

This trace is encoded in a trie format similar to the GeckoProfiler and Chrome tracing formats -- see the appendix for an overview of how stacks are represented.

An example of how you might want to profile a pageload for server-side analysis is below:

const profiler = new Profiler({
  sampleInterval: 10,      // Target sampling every 10ms
  maxBufferSize: 10 * 100, // Cap at ~10s worth of samples
});

async function collectAndSendTrace() {
  if (profiler.stopped) return;

  const trace = await profiler.stop();
  const traceJson = JSON.stringify({
    timing: performance.timing,
    trace,
  });

  // Send the trace JSON to a server via Fetch/XHR
  sendTrace(traceJson);
}

profiler.addEventListener('samplebufferfull', collectAndSendTrace);
window.addEventListener('load', collectAndSendTrace);

// Rest of the page's JS initialization logic

Markers Extensions

See markers for detailed description of the proposal.

Privacy and Security

See the Privacy and Security section of the spec.

Appendix: Profile Format

A trie-like approach is chosen for representing traces obtained from the profiler. There are examples of trie-based approaches in browsers today:

The API aims to provide deduplication of script resource URLs, stack frames, and stack sequences (through the aforementioned trie approach) to reduce memory pressure and trace size when sent over the network.

The specification's processing model provides detail on how these traces are constructed. An example (encoded in JSON) can be found below:

{
  "resources" : [
    "https://static.xx.fbcdn.net/rsrc.php/v3/yW/r/ZgaPtFDHPeq.js",
    "https://static.xx.fbcdn.net/rsrc.php/v3iMKu4/yW/l/en_US-i/gSq3sO3PcU1.js"
  ],
  "stacks" : [
    {
      "frameId" : 0
    },
    {
      "frameId" : 1,
      "parentId" : 0
    },
    {
      "frameId" : 2,
      "parentId" : 1
    }
  ],
  "samples" : [
    {
      "timestamp" : 1551.73499998637,
      "stackId": 2
    },
    {
      "timestamp" : 1576.83999999426,
      "stackId": 1
    },
    {
      "timestamp" : 1601.90499993041
    }
  ],
  "frames" : [
    {
      "name" : "b",
      "resourceId" : 0,
      "line" : 23,
      "column" : 169
    },
    {
      "name" : "l",
      "resourceId": 1,
      "line" : 313,
      "column" : 468
    },
    {
      "name" : "a",
      "resourceId": 1,
      "line" : 313,
      "column" : 1325
    }
  ]
}

The API may also be combined with other APIs such as Compression Streams in order to further reduce trace size.

Visualization

Mozilla's perf.html visualization tool for Firefox profiles or Chrome's trace-viewer (chrome://tracing) UI could be trivially adapted to visualize the data produced by this profiling API.

perf.html

As an illustration, a screenshot below from Mozilla's perf.html project shows the JS stack aggregation and timeline. It is able to show gaps where JavaScript was not executing, areas where there were long running events (red), and an aggregate view of the samples in the selected time range such as the 15 contiguous samples in function 'user.ts' highlighted in the screenshot below.

Mozilla's perf.html UI for visualizing Gecko profiles

More Repositories

1

webcomponents

Web Components specifications
HTML
4,360
star
2

import-maps

How to control the behavior of JavaScript imports
JavaScript
2,705
star
3

virtual-scroller

1,998
star
4

focus-visible

Polyfill for `:focus-visible`
JavaScript
1,607
star
5

webusb

Connecting hardware to the web.
Bikeshed
1,310
star
6

webpackage

Web packaging format
Go
1,231
star
7

EventListenerOptions

An extension to the DOM event pattern to allow authors to disable support for preventDefault
JavaScript
1,166
star
8

portals

A proposal for enabling seamless navigations between sites or pages
HTML
946
star
9

floc

This proposal has been replaced by the Topics API.
Makefile
934
star
10

inert

Polyfill for the inert attribute and property.
JavaScript
920
star
11

scheduling-apis

APIs for scheduling and controlling prioritized tasks.
HTML
909
star
12

view-transitions

811
star
13

file-system-access

Expose the file system on the user’s device, so Web apps can interoperate with the user’s native applications.
Bikeshed
658
star
14

background-sync

A design and spec for ServiceWorker-based background synchronization
HTML
639
star
15

ua-client-hints

Wouldn't it be nice if `User-Agent` was a (set of) client hints?
Bikeshed
590
star
16

scroll-to-text-fragment

Proposal to allow specifying a text snippet in a URL fragment
HTML
586
star
17

observable

Observable API proposal
Bikeshed
582
star
18

aom

Accessibility Object Model
HTML
567
star
19

kv-storage

[On hold] A proposal for an async key/value storage API for the web
550
star
20

turtledove

TURTLEDOVE
Bikeshed
526
star
21

navigation-api

The new navigation API provides a new interface for navigations and session history, with a focus on single-page application navigations.
Makefile
486
star
22

webmonetization

Proposed Web Monetization standard
HTML
461
star
23

trust-token-api

Trust Token API
Bikeshed
421
star
24

attribution-reporting-api

Attribution Reporting API
Bikeshed
360
star
25

direct-sockets

Direct Sockets API for the web platform
HTML
329
star
26

shape-detection-api

Detection of shapes (faces, QR codes) in images
Bikeshed
304
star
27

display-locking

A repository for the Display Locking spec
HTML
297
star
28

dbsc

Bikeshed
297
star
29

background-fetch

API proposal for background downloading/uploading
Shell
281
star
30

first-party-sets

Bikeshed
280
star
31

serial

Serial ports API for the platform.
HTML
256
star
32

resize-observer

This repository is no longer active. ResizeObserver has moved out of WICG into
HTML
255
star
33

priority-hints

A browser API to enable developers signal the priorities of the resources they need to download.
Bikeshed
249
star
34

sanitizer-api

Bikeshed
227
star
35

is-input-pending

HTML
221
star
36

proposals

A home for well-formed proposed incubations for the web platform. All proposals welcome.
216
star
37

spatial-navigation

Directional focus navigation with arrow keys
JavaScript
212
star
38

cq-usecases

Use cases and requirements for standardizing element queries.
HTML
184
star
39

isolated-web-apps

Repository for explainers and other documents related to the Isolated Web Apps proposal.
Bikeshed
182
star
40

visual-viewport

A proposal to add explicit APIs to the Web for querying and setting the visual viewport
HTML
177
star
41

interventions

A place for browsers and web developers to collaborate on user agent interventions.
176
star
42

frame-timing

Frame Timing API
HTML
170
star
43

layout-instability

A proposal for a Layout Instability specification
Makefile
158
star
44

page-lifecycle

Lifecycle API to support system initiated discarding and freezing
HTML
154
star
45

nav-speculation

Proposal to enable privacy-enhanced preloading
HTML
154
star
46

speech-api

Web Speech API
Bikeshed
145
star
47

cookie-store

Asynchronous access to cookies from JavaScript
Bikeshed
143
star
48

construct-stylesheets

API for constructing CSS stylesheet objects
Bikeshed
137
star
49

webhid

Web API for accessing Human Interface Devices (HID)
HTML
137
star
50

color-api

A proposal and draft spec for a Color object for the Web Platform, loosely influenced by the Color.js work. Heavily WIP, if you landed here randomly, please move along.
HTML
132
star
51

fenced-frame

Proposal for a strong boundary between a page and its embedded content
Bikeshed
126
star
52

devtools-protocol

DevTools Protocol
JavaScript
120
star
53

sms-one-time-codes

A way to format SMS messages for use with browser autofill features such as HTML’s autocomplete=one-time-code.
Makefile
111
star
54

bundle-preloading

Bundles of multiple resources, to improve loading JS and the Web.
HTML
105
star
55

translation-api

A proposal for translator and language detector APIs
Bikeshed
104
star
56

privacy-preserving-ads

Privacy-Preserving Ads
HCL
100
star
57

manifest-incubations

Before install prompt API for installing web applications
HTML
99
star
58

window-controls-overlay

HTML
97
star
59

netinfo

HTML
95
star
60

compression-dictionary-transport

94
star
61

intrinsicsize-attribute

Proposal to add an intrinsicsize attribute to media elements
93
star
62

animation-worklet

🚫 Old repository for AnimationWorklet specification ➡️ New repository: https://github.com/w3c/css-houdini-drafts
Makefile
92
star
63

container-queries

HTML
91
star
64

local-peer-to-peer

↔️ Proposal for local communication between browsers without the aid of a server.
Bikeshed
90
star
65

shared-storage

Explainer for proposed web platform Shared Storage API
Bikeshed
89
star
66

async-append

A way to create DOM and add it to the document without blocking the main thread.
HTML
87
star
67

indexed-db-observers

Prototyping and discussion around indexeddb observers.
WebIDL
84
star
68

canvas-formatted-text

HTML
82
star
69

file-handling

API for web applications to handle files
82
star
70

canvas-color-space

Proposed web platform feature to add color management, wide gamut and high bit-depth support to the <canvas> element.
79
star
71

local-font-access

Web API for enumerating fonts on the local system
Bikeshed
77
star
72

performance-measure-memory

performance.measureMemory API
HTML
77
star
73

digital-credentials

Digital Credentials, like driver's licenses
HTML
77
star
74

handwriting-recognition

Handwriting Recognition Web API Proposal
Bikeshed
75
star
75

web-app-launch

Web App Launch Handler
HTML
75
star
76

pwa-url-handler

72
star
77

ContentPerformancePolicy

A set of policies that a site guarantees to adhere to, browsers enforce, and embedders can count on.
HTML
72
star
78

starter-kit

A simple starter kit for incubations
JavaScript
72
star
79

css-parser-api

This is the repo where the CSS Houdini parser API will be worked on
HTML
71
star
80

close-watcher

A web API proposal for watching for close requests (e.g. Esc, Android back button, ...)
Makefile
71
star
81

eyedropper-api

HTML
69
star
82

idle-detection

A proposal for an idle detection and notification API for the web
Bikeshed
67
star
83

storage-foundation-api-explainer

Explainer showcasing a new web storage API, NativeIO
65
star
84

video-editing

65
star
85

uuid

UUID V4
63
star
86

client-hints-infrastructure

Specification for the Client Hints infrastructure - privacy preserving proactive content negotiation
Bikeshed
61
star
87

sparrow

60
star
88

private-network-access

HTML
58
star
89

element-timing

A proposal for an Element Timing specification.
Bikeshed
57
star
90

document-picture-in-picture

Bikeshed
56
star
91

video-rvfc

video.requestVideoFrameCallback() incubation
HTML
53
star
92

time-to-interactive

Repository for hosting TTI specification and discussions around it.
52
star
93

digital-goods

Bikeshed
50
star
94

soft-navigations

Heuristics to detect Single Page Apps soft navigations
Bikeshed
46
star
95

raw-clipboard-access

An explainer for the Raw Clipboard Access feature
44
star
96

storage-buckets

API proposal for managing multiple storage buckets
Bikeshed
43
star
97

pending-beacon

A better beaconing API
Bikeshed
43
star
98

admin

👋 Ask your questions here! 👋
HTML
42
star
99

web-smart-card

Repository for the Web Smart Card Explainer
HTML
42
star
100

web-preferences-api

The Web Preference API aims to provide a way for sites to override the value for a given user preference (e.g. color-scheme preference) in a way that fully integrates with existing Web APIs.
Bikeshed
41
star