Performance Measurement Utility for Browser
Functions
Here's a comprehensive utility library that measures and stores performance
data for both synchronous and asynchronous functions using the Browser
Performance API:
/**
* Performance measurement utility for browser functions
*/
class PerfMetrics {
constructor() {
[Link] = new Map();
[Link] = [Link] || [Link]
|| [Link] || [Link];
if (![Link]) {
[Link]('Performance API not supported in this browser');
}
}
/**
* Measure performance of a synchronous function
* @param {Function} fn - The function to measure
* @param {string} name - Unique identifier for this measurement
* @param {...any} args - Arguments to pass to the function
* @returns {any} The result of the function execution
*/
measureSync(fn, name, ...args) {
if (typeof fn !== 'function') {
throw new Error('First argument must be a function');
}
if (![Link]) return fn(...args);
const startMark = `${name}-start`;
const endMark = `${name}-end`;
const measureName = name;
// Set marks for precise measurement
[Link](startMark);
try {
const result = fn(...args);
[Link](endMark);
[Link](measureName, startMark, endMark);
this._storeMeasurement(name);
return result;
} catch (error) {
[Link](endMark);
[Link](measureName, startMark, endMark);
this._storeMeasurement(name, error);
throw error;
} finally {
this._cleanupMarks(startMark, endMark, measureName);
}
}
/**
* Measure performance of an asynchronous function
* @param {Function} asyncFn - The async function to measure
* @param {string} name - Unique identifier for this measurement
* @param {...any} args - Arguments to pass to the function
* @returns {Promise<any>} Promise that resolves with the function's
result
*/
async measureAsync(asyncFn, name, ...args) {
if (typeof asyncFn !== 'function') {
throw new Error('First argument must be a function');
}
if (![Link]) return asyncFn(...args);
const startMark = `${name}-start`;
const endMark = `${name}-end`;
const measureName = name;
[Link](startMark);
try {
const result = await asyncFn(...args);
[Link](endMark);
[Link](measureName, startMark, endMark);
this._storeMeasurement(name);
return result;
} catch (error) {
[Link](endMark);
[Link](measureName, startMark, endMark);
this._storeMeasurement(name, error);
throw error;
} finally {
this._cleanupMarks(startMark, endMark, measureName);
}
}
/**
* Store measurement data
* @private
* @param {string} name - Measurement name
* @param {Error} [error] - Optional error object
*/
_storeMeasurement(name, error) {
const measures = [Link](name);
if ([Link] === 0) return;
const lastMeasure = measures[[Link] - 1];
const metric = {
name,
duration: [Link],
startTime: [Link],
entryType: [Link],
timestamp: [Link](),
error: error ? [Link] : null
};
if () {
[Link](name, []);
}
[Link](name).push(metric);
}
/**
* Clean up performance marks and measures
* @private
* @param {string} startMark - Start mark name
* @param {string} endMark - End mark name
* @param {string} measureName - Measure name
*/
_cleanupMarks(startMark, endMark, measureName) {
[Link](startMark);
[Link](endMark);
[Link](measureName);
}
/**
* Get all stored metrics
* @returns {Array} Array of all stored metrics
*/
getAllMetrics() {
return [Link]([Link]()).flat();
}
/**
* Get metrics by name
* @param {string} name - The metric name to retrieve
* @returns {Array|null} Array of metrics or null if not found
*/
getMetricsByName(name) {
return [Link](name) || null;
}
/**
* Clear all stored metrics
*/
clearMetrics() {
[Link]();
}
/**
* Get performance statistics for a named metric
* @param {string} name - The metric name
* @returns {Object} Object containing statistics
*/
getStats(name) {
const metrics = [Link](name);
if (!metrics || [Link] === 0) return null;
const durations = [Link](m => [Link]);
const successful = [Link](m => ![Link]).length;
const failed = [Link](m => [Link]).length;
return {
count: [Link],
successful,
failed,
avgDuration: [Link]((sum, d) => sum + d, 0) /
[Link],
minDuration: [Link](...durations),
maxDuration: [Link](...durations),
totalDuration: [Link]((sum, d) => sum + d, 0),
lastDuration: durations[[Link] - 1]
};
}
}
// Export as module
export default PerfMetrics;
Features
1. Supports both synchronous and asynchronous functions
o measureSync() for synchronous functions
o measureAsync() for async functions/Promises
2. Comprehensive Performance API usage
o Uses [Link]() and [Link]()
o Proper cleanup of marks and measures to prevent memory leaks
3. Storage and retrieval of metrics
o Stores all measurements with timestamps
o Provides methods to retrieve metrics by name or get all metrics
4. Error handling
o Captures errors during function execution
o Includes error information in metrics
5. Performance statistics
o Calculates min, max, and average durations
o Tracks success/failure counts
Usage Examples
const perf = new PerfMetrics();
// Measure synchronous function
const result = [Link](() => {
// Some heavy computation
let sum = 0;
for (let i = 0; i < 1000000; i++) {
sum += [Link]();
}
return sum;
}, 'random-sum');
// Measure asynchronous function
await [Link](async () => {
await fetch('[Link]
}, 'api-fetch');
// Get statistics
const stats = [Link]('api-fetch');
[Link]('Average duration:', [Link]);
This utility provides a robust way to track performance metrics in your
application while maintaining clean usage of the Performance API.