From 65f9ba8f1c1fe16f0335050b81a22106beeb3a70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kevin=20Gr=C3=BCneberg?= Date: Tue, 14 Sep 2021 13:47:51 +0200 Subject: [PATCH] perf: speed up date formatting --- bench.js | 28 ++++++++++++++++++++++++++++ index.js | 5 +---- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/bench.js b/bench.js index b3bfe212..9ae503e8 100644 --- a/bench.js +++ b/bench.js @@ -50,22 +50,38 @@ const arraySchemaCJS = { items: schemaCJS } +const dateFormatSchema = { + description: 'Date of birth', + type: 'string', + format: 'date' +} + +const dateFormatSchemaCJS = { + description: 'Date of birth', + type: 'string', + format: 'date' +} + const obj = { firstName: 'Matteo', lastName: 'Collina', age: 32 } +const date = new Date() + const multiArray = [] const CJS = require('compile-json-stringify') const CJSStringify = CJS(schemaCJS) const CJSStringifyArray = CJS(arraySchemaCJS) +const CJSStringifyDate = CJS(dateFormatSchemaCJS) const CJSStringifyString = CJS({ type: 'string' }) const FJS = require('.') const stringify = FJS(schema) const stringifyArray = FJS(arraySchema) +const stringifyDate = FJS(dateFormatSchema) const stringifyString = FJS({ type: 'string' }) let str = '' @@ -138,6 +154,18 @@ suite.add('compile-json-stringify obj', function () { CJSStringify(obj) }) +suite.add('JSON stringify date', function () { + JSON.stringify(date) +}) + +suite.add('fast-json-stringify date format', function () { + stringifyDate(date) +}) + +suite.add('compile-json-stringify date format', function () { + CJSStringifyDate(date) +}) + suite.on('cycle', cycle) suite.run() diff --git a/index.js b/index.js index 3ce3fba9..6369be6d 100644 --- a/index.js +++ b/index.js @@ -285,10 +285,7 @@ function $asDatetime (date, skipQuotes) { function $asDate (date, skipQuotes) { const quotes = skipQuotes === true ? '' : '"' if (date instanceof Date) { - const year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date) - const month = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(date) - const day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date) - return quotes + year + '-' + month + '-' + day + quotes + return quotes + new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )).toISOString().slice(0, 10) + quotes } else if (date && typeof date.format === 'function') { return quotes + date.format('YYYY-MM-DD') + quotes } else {