DEV Community 👩‍💻👨‍💻

Jeongho Nam
Jeongho Nam

Posted on • Updated on

I made 10x faster JSON.stringify() functions, even type safe

// FASTER STRINGIFY FUNCTIONS
export function stringify<T>(input: T): string; // unsafe but fatest
export function assertStringify<T>(input: T): string; // throws TypeGuardError
export function isStringify<T>(input: T): string | null; // wrong type be null

// RUNTIME VALIDATORS ALLOWING SUPERFLUOUS PROPERTIES
export function is<T>(input: unknown): input is T; // returns boolean
export function assertType<T>(input: unknown): T; // throws TypeGuardError
export function validate<T>(input: unknown): IValidation; // detailed reasons

// DO NOT ALLOW SUPERFLUOUS PROPERTIES
export function equals<T>(input: unknown): input is T;
export function assertType<T>(input: unknown): T;
export function validate<T>(input: unknown): IValidation;
Enter fullscreen mode Exit fullscreen mode

Hello, I'm a developer of typescript-json, which can validate instance type by only one line, what I'd introduced as "1,000x faster runtime validator library" in here dev.to. In today, I came back with powerful JSON string conversion functions.

As you can see from the above code, the new JSON string conversion functions throw TypedGuardError or return null value when input value is different with target type T. One thing amazing is, those JSON string conversion functions are much faster than the native JSON.stringify() function despite of type validation process.

JSON string conversion speed

Of course, as this benchmark measured by myself, someone can doubt its objectivity.

Therefore, to ensure the objectivity, I diclose all code used in the benchmark. Below codes are being used in the benchmark. You also can run the benchmark program by running npm install and npm run benchmark commands after cloning typescript-json repository.

How to use

If you want to utilize those type safe JSON functions, just install and import typescript-json. After that, call those functions like below. You don't need to define any extra dedication like fast-json-stringify which requires JSON schema definition. Only you need is only one line with pure TypeScript type.

Note that, TSON.assertStringify() function throws TypeGuardError exception and TSON.isStringify() function returns boolean value when parametric input value is different with the target type T. Of course, if input value is matched with the type T, just JSON string would be returned. Anyway, choose one of them depending on your purpose.

import TSON from "typescript-json";

interface IMember {
    name: string;
    age: number;
}

// NO PROBLEM
const exact: IMember = { name: "someone", age: 0 };
TSON.assertStringify(exact);
TSON.isStringify(exact);

// WRONG TYPE
const wrong: IMember = { name: "someone", age: false as any };
TSON.assertStringify(wrong); // throws TypeGuardError
TSON.isStringify(wrong); // returns null
Enter fullscreen mode Exit fullscreen mode

How can be such faster

AOT (Ahead of Time) compilation.

typescript-json analyzes your code (type T) in the compilation level and generates optimized runtime code for JSON string conversion. Such optimized runtime code generation by analzying source code is called AOT (Ahead of Time) compilation and it is the reason why typescript-json's JSON string conversion functions are much faster than the native JSON.stringify() function despite of type validation process.

In the same reason, validation functions of typescript-json are much faster than other validation libraries. Only TypeBox can be competitive and TypeBox utilizes JIT (Just-in-time) compilation. Other libraries without special skills are extremely slow, and the gap can widen by thousands of times.

Someone may have question, "Why are you comparing with other validator libraries? Where's the other JSON string converter library?" Unfortunately, there's not any other library that can convert JSON string safely like typescript-json. Therefore, I had to compare with validator libraries. Please understand me and such circumstance.

is() function benchmark

assertType() function benchmark

Full Spec of TypeScript Type

typescript-json supports full spec of TypeScript type.

Therefore, use TSON.assertStringify() and TSON.isStringify() functions enhance your program's type safety with confidence. I hope those functions to be really useful for network systems using JSON data, especially for enhancing type safety.

Components TSON TypeBox ajv io-ts zod C.V.
Easy to use ✅ ❌ ❌ ❌ ❌ ❌
Object (simple) ✔ ✔ ✔ ✔ ✔ ✔
Object (hierarchical) ✔ ✔ ❌ ✔ ✔ ✔
Object (recursive) ✔ ✔ ✔ ✔ ✔ ✔
Object (union, implicit) ✅ ❌ ❌ ❌ ❌ ❌
Object (union, explicit) ✔ ✔ ✔ ✔ ✔ ❌
Object (additional tags) ✔ ✔ ✔ ✔ ✔ ✔
Object (template literal types) ✔ ✔ ✔ ❌ ❌ ❌
Object (dynamic properties) ✔ ✔ ✔ ❌ ❌ ❌
Array (hierarchical) ✔ ✔ ✔ ✔ ✔ ✔
Array (recursive) ✔ ✔ ✔ ✔ ✔ ❌
Array (recursive, union) ✔ ✔ ❌ ✔ ✔ ❌
Array (R+U, implicit) ✅ ❌ ❌ ❌ ❌ ❌
Ultimate Union Type ✅ ❌ ❌ ❌ ❌ ❌
  • TSON: typescript-json
  • C.V.: class-validator

Top comments (12)

Collapse
 
arsalannury profile image
ArsalanNury

i reading document of this package and it is easy to learn . thank you

Collapse
 
dendihandian profile image
Dendi Handian

Gonna read this later

Collapse
 
rida profile image
Rida F'kih

Interesting, are you using TypeScript transformers to generate the validation objects during compilation?

Collapse
 
samchon profile image
Jeongho Nam

Yes, utilizing ttypescript

Collapse
 
wadecodez profile image
Wade Zimmerman

So basically this library is faster than the native stringify because it's defining a schema ahead of time?

If so, I'm curious how this would work with applications with large amount of data. Would it slow down the initial page load?

Collapse
 
samchon profile image
Jeongho Nam

Bundle size of typescript-json is extremely small (as it works only in compilation process) and generated code by typescript-json not such small. Therefore, I think it does not effect on initial page loading unless you've defined typescript-json function calling code over thousands of times.

Collapse
 
vineyrawat profile image
Viney Rawat

Good post

Collapse
 
glowreeyah profile image
Gloria Asuquo

This is so educative

Collapse
 
sanjeevkse profile image
sanjeev shetty

Gonna read this later

Collapse
 
mrrightp profile image
Right possible

can it be use with normal javascript???

Collapse
 
samchon profile image
Jeongho Nam

Not possible in pure JavaScript. However, detour way like building reusable functions in TypeScript and importing them in JavaScript is possible.

Collapse
 
tienthanhjlw profile image
Nguyễn Tiến Thành

thank you!

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.