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

perf: optimize json string escaping #1717

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

ivan-tymoshenko
Copy link

@ivan-tymoshenko ivan-tymoshenko commented May 17, 2023

Similar PR for the same escaping function.
fastify/fast-json-stringify#553

Comment on lines +76 to +78
// eslint-disable-next-line
const STR_ESCAPE = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is very mysterious (i.e. I have no clue what it is looking for and don't want to expend the mental gymnastics to figure it out). If we are going to introduce complicated regular expressions, I'd rather see https://www.npmjs.com/package/xregexp used to make them legible.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This contains the groups of chars that should be escaped. Not sure if this can be not mysterious.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Roughly:

https://runkit.com/embed/rx8essijm0uh

var xregexp = require("xregexp")

const STR_ESCAPE = xregexp(
  `[\u0000-\u001f\u0022\u005c\ud800-\udfff] # chars A - G
  | [\ud800-\udbff] # chars H - J
  (?![\udc00-\udfff]) # BUT NOT something else
  | (?:[^\ud800-\udbff]|^) # some explantation
  [\udc00-\udfff] # something else
  `
  ,
  'x'
)

It's clearer, but could probably be even more clear using XRegExp.build.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A jsdoc block that explains each part would also suffice (and keep a concerning dependency tree from being added).

Copy link
Member

@mcollina mcollina left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants