Skip to content

Commit

Permalink
fix: use native performance object in Node 18 (#38)
Browse files Browse the repository at this point in the history
Fixes #17
  • Loading branch information
nolanlawson committed Jul 4, 2022
1 parent 97c4650 commit 4933c46
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 11 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test_node.yml
Expand Up @@ -7,7 +7,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node: [ '12', '14', '16' ]
node: [ '12', '14', '16', '18' ]
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
Expand Down
12 changes: 11 additions & 1 deletion src/index.js
Expand Up @@ -31,9 +31,19 @@ let clear
if (
perf &&
perf.mark &&
perf.measure &&
perf.getEntriesByName &&
perf.getEntriesByType &&
perf.clearMeasures
perf.clearMarks &&
perf.clearMeasures &&
// In Node, we want to detect that this perf/correctness fix [1] is available, which
// landed in Node 16.15.0, 17.6.0, and 18.0.0. However, it's not observable, and
// we don't want to rely on fragile version checks.
// So we can rely on this observable change [2] to add clearResourceTimings, which
// landed a bit later (18.2.0), but is close enough for our purposes.
// [1]: https://github.com/nodejs/node/pull/42032
// [2]: https://github.com/nodejs/node/pull/42725
(process.browser || perf.clearResourceTimings)
) {
mark = name => {
throwIfEmpty(name)
Expand Down
10 changes: 5 additions & 5 deletions src/now.js
@@ -1,6 +1,6 @@
import perf from './performance'

let nowForNode
let nowPolyfillForNode

if (!process.browser) {
// implementation borrowed from:
Expand All @@ -11,9 +11,9 @@ if (!process.browser) {
return hr[0] * 1e9 + hr[1]
}
const loadTime = getNanoSeconds()
nowForNode = () => ((getNanoSeconds() - loadTime) / 1e6)
nowPolyfillForNode = () => ((getNanoSeconds() - loadTime) / 1e6)
}

export default process.browser
? perf && perf.now ? () => perf.now() : () => Date.now()
: nowForNode
export default perf && perf.now
? () => perf.now()
: process.browser ? () => Date.now() : nowPolyfillForNode
5 changes: 1 addition & 4 deletions src/performance.js
@@ -1,5 +1,2 @@
/* global performance */

// TODO: Node's built-in performance API has poor performance for getEntriesByName()
// so currently we avoid it: https://github.com/nolanlawson/marky/issues/29
export default process.browser && typeof performance !== 'undefined' && performance
export default typeof performance !== 'undefined' && performance

0 comments on commit 4933c46

Please sign in to comment.