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

fix(gatsby): quick check if string looks like a date #12700

Merged
merged 1 commit into from
Mar 21, 2019
Merged
Changes from all commits
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
7 changes: 6 additions & 1 deletion packages/gatsby/src/schema/types/date.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,13 @@ const GraphQLDate = new GraphQLScalarType({
// Check if this is a date.
// All the allowed ISO 8601 date-time formats used.
function isDate(value) {
// quick check if value does not look like a date
if (typeof value === `number` || !/^\d{4}/.test(value)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm not sure an inline regex is the fastest way of determining if the first 4 values are numeric.

You could pre-compile, or alternatively even have a set of possible single digit strings, and iterate over the first 4 and break if it's not in the set.

Copy link
Contributor

Choose a reason for hiding this comment

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

According to this benchmark, it seems inline regex or pre-compiled is actually fastest.

https://jsperf.com/check-whether-string-starts-with-four-numbers

In Chrome it doesn't appear to matter if it's inline or not, in Safari I notice a 2% improvement in pre-compiling.

Copy link
Contributor

Choose a reason for hiding this comment

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

I tried both ways and the change was marginal, about 600s to build the schemas. Without the patch, it was 8000s. My guess is that the regex is optimized automatically.

Copy link
Contributor Author

@wardpeet wardpeet Mar 21, 2019

Choose a reason for hiding this comment

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

@me4502 I used string.slice(0, 4) and checked if it was a number and regex was faster. I'm pretty sure v8 optimizes for it. node is using v8 = chrome so we're probably good.

@millette at least we got somewhere, not fast enough but faster.

return false
}

const momentDate = moment.utc(value, ISO_8601_FORMAT, true)
return momentDate.isValid() && typeof value !== `number`
return momentDate.isValid()
}

const formatDate = ({
Expand Down