Merge "resourceloader: Simplify StringSet fallback"
[lhc/web/wiklou.git] / resources / src / startup / profiler.js
1 /*!
2 * Augment mw.loader to facilitate module-level profiling.
3 *
4 * @author Timo Tijhof
5 * @since 1.32
6 */
7 /* global mw */
8 ( function () {
9 'use strict';
10
11 var moduleTimes = Object.create( null );
12
13 /**
14 * Private hooks inserted into mw.loader code if MediaWiki configuration
15 * `$wgResourceLoaderEnableJSProfiler` is `true`.
16 *
17 * To use this data, run `mw.inspect( 'time' )` from the browser console.
18 * See mw#inspect().
19 *
20 * @private
21 * @class
22 * @singleton
23 */
24 mw.loader.profiler = {
25 onExecuteStart: function ( moduleName ) {
26 var time = performance.now();
27 if ( moduleTimes[ moduleName ] ) {
28 throw new Error( 'Unexpected perf record for "' + moduleName + '".' );
29 }
30 moduleTimes[ moduleName ] = {
31 executeStart: time,
32 executeEnd: null,
33 scriptStart: null,
34 scriptEnd: null
35 };
36 },
37 onExecuteEnd: function ( moduleName ) {
38 var time = performance.now();
39 moduleTimes[ moduleName ].executeEnd = time;
40 },
41 onScriptStart: function ( moduleName ) {
42 var time = performance.now();
43 moduleTimes[ moduleName ].scriptStart = time;
44 },
45 onScriptEnd: function ( moduleName ) {
46 var time = performance.now();
47 moduleTimes[ moduleName ].scriptEnd = time;
48 },
49
50 /**
51 * For internal use by inspect.reports#time.
52 *
53 * @private
54 * @param {string} moduleName
55 * @return {Object|null}
56 * @throws {Error} If the perf record is incomplete.
57 */
58 getProfile: function ( moduleName ) {
59 var times, key, execute, script, total;
60 times = moduleTimes[ moduleName ];
61 if ( !times ) {
62 return null;
63 }
64 for ( key in times ) {
65 if ( times[ key ] === null ) {
66 throw new Error( 'Incomplete perf record for "' + moduleName + '".', times );
67 }
68 }
69 execute = times.executeEnd - times.executeStart;
70 script = times.scriptEnd - times.scriptStart;
71 total = execute + script;
72 return {
73 name: moduleName,
74 execute: execute,
75 script: script,
76 total: total
77 };
78 }
79 };
80
81 }() );