Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance improvements #80

Merged
merged 18 commits into from
Jan 12, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
perf(Output): Use template strings rather than JSON.stringify
Before:

logga x 469,130 ops/sec ±0.11% (593 runs sampled)

After:

logga x 763,432 ops/sec ±0.18% (591 runs sampled)
  • Loading branch information
nokome committed Jan 11, 2021
commit e33e2f31f5eb40b9bdc90fa423491f4716163b12
44 changes: 39 additions & 5 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,37 @@ export function replaceHandlers(handler: LogHandler): void {

const defaultHandlerHistory = new Map<string, number>()

/**
* Escape a string for inclusion in JSON.
*
* Based on the list at https://www.json.org minus the backspace character (U+0008)
*
* @param value The string to escape
*/
function escape(value: string): string {
return value !== undefined
? value.replace(/\"|\\|\/|\f|\n|\r|\t/g, (char) => {
switch (char) {
case '"':
return '"'
case '\\':
return '\\\\'
case '/':
return '\\/'
case '\f':
return '\\f'
case '\n':
return '\\n'
case '\r':
return '\\r'
case '\t':
return '\\t'
}
return char
})
: value
}

/**
* Default log event handler.
*
Expand Down Expand Up @@ -286,10 +317,13 @@ export function defaultHandler(
process.stderr.isTTY !== true
) {
const { fastTime = false } = options
entry = JSON.stringify({
time: fastTime ? Date.now() : new Date().toISOString(),
...data,
})
entry = `{"time":${
fastTime ? Date.now() : `"${new Date().toISOString()}"`
},"tag":"${tag}","level":${level},"message":"${message}"`
if (stack !== undefined) {
entry += `,"stack":"${escape(stack)}"`
}
entry += '}\n'
} else {
const index = level < 0 ? 0 : level > 3 ? 3 : level
const label = LogLevel[index].toUpperCase().padEnd(5, ' ')
Expand Down Expand Up @@ -321,7 +355,7 @@ export function defaultHandler(
// On Node.js, writing directly to stderr provides a performance boost
// of ~ 150% (based on our benchmarking)
if (typeof process !== 'undefined') {
process.stderr.write(entry + '\n')
process.stderr.write(entry)
} else {
console.error(entry)
}
Expand Down