1.0.0 • Published 1 year ago

fast-iso-string v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

npm package Build Status Downloads Issues Code Coverage Commitizen Friendly Semantic Release

A way to get the ISO String about 120%~130% faster than using new Date().toISOString().

Here's a C++ code rewrite to TypeScript from V8 to get a faster ISO String format date.

See here the original implementation.

Usage

First, install the library:

npm i fast-iso-string

Then, you have two exposed methods that you can use:

  • fastISOString: That returns the current date as ISO String.
  • fromUnixToISOString: To parse a unix time that you already have.

And then use like this:

import { fastISOString } from 'fast-iso-string';

-const isoString = new Date().toISOString();
+const isoString = fastISOString();

Benchmarks

Above, the difference of calling new Date().toISOString() or using the library.

new Date().toISOString() x 1,419,493 ops/sec ±2.00% (85 sampled runs)
fastISOString() x 3,306,564 ops/sec ±2.75% (85 sampled runs)

Why is fast?

Well, I have two reasons:

  • Avoiding creating new Date(), actually, using just Date.now() is almost 100% faster than calling new Date().
  • JS->C++ cost, this is a hidden cost of calling V8 to perform that operation, I don't know exactly the cost but I think that contribute to the slowdown.

Is fair to compare new Date against Date.now?

You might consider this benchmark unfair because I'm using Date.now() instead of new Date(). Actually yeah it's not fair, if we use fromUnixToISOString(new Date()) it might be slower as per this and this.

But otherwise, do you know how to get ISO String without calling new Date()? I don't know, so JavaScript for us to use the Date object, so I just skip that runtime cost and go directly to what I want, the formatted ISO String, which format you get the start date in doesn't matter.

This also leaves a question: so everything I'm doing with new Date().MY_METHOD could be faster? Maybe yes. If you parse unix time and extract the information in whatever format you want it could be faster. I just created one of the Date methods, but you can try and see if you get faster results with other methods.

Should I use this library?

If you're doing a lot of operations that need to use the ISO String, maybe you should.

It's not because I'm saying that one method is faster than the other, that this will bring some performance improvement to your workflow, the best thing you can do is to do a benchmarking, to learn more, see Preparing and Evaluating Benchmarks by @RafaelGSS.

Thanks

I need to thank @RafaelGSS for inspiring the creation of this library for his work on performance within NodeJs.