# Performance API

The Performance API provides access to performance-related information for the current page. It allows you to measure the performance of your web applications with high precision.

## 1. `performance.now()` vs `Date.now()`

`Date.now()` returns the number of milliseconds since the Unix Epoch (Jan 1, 1970). It is based on the system clock, which can be adjusted (skewed) and is not monotonic.

`performance.now()` returns a `DOMHighResTimeStamp`, measured in milliseconds, accurate to 5 microseconds (subject to browser security constraints). It is monotonic (always increasing) and relative to the `performance.timeOrigin` (usually page load start).

```javascript
const start = performance.now();

// Do some work
for (let i = 0; i < 1000000; i++) {}

const end = performance.now();
console.log(`Execution time: ${end - start} milliseconds`);
```

## 2. User Timing API

You can create custom performance markers and measures to track specific parts of your code.

### `performance.mark()`
Creates a timestamp with a name in the browser's performance entry buffer.

```javascript
performance.mark('login-start');
// ... login logic ...
performance.mark('login-end');
```

### `performance.measure()`
Calculates the duration between two marks.

```javascript
performance.measure('login-duration', 'login-start', 'login-end');

// Retrieve the measure
const measures = performance.getEntriesByName('login-duration');
console.log(measures[0].duration);
```

## 3. Resource Timing API

The browser automatically records timing data for resources (images, scripts, CSS) loaded by the page.

```javascript
const resources = performance.getEntriesByType('resource');

resources.forEach((resource) => {
  console.log(`Name: ${resource.name}`);
  console.log(`Type: ${resource.initiatorType}`);
  console.log(`Duration: ${resource.duration}`);
});
```

## 4. PerformanceObserver

The `PerformanceObserver` interface is used to observe performance measurement events and be notified of new performance entries as they happen. This is preferred over polling `getEntries()`.

```javascript
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(`${entry.name}: ${entry.duration}ms`);
  });
});

// Observe specific entry types
observer.observe({ entryTypes: ['measure', 'resource'] });
```

## 5. Navigation Timing

Provides data about the page's load performance (DNS lookup, TCP connection, DOM loading, etc.).

```javascript
const navigation = performance.getEntriesByType('navigation')[0];
console.log(`DOM Content Loaded: ${navigation.domContentLoadedEventEnd - navigation.startTime}`);
```

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/date-and-time]]