samchon / typia

Super-fast/easy runtime validators and serializers via transformation
https://typia.io/
MIT License
4.65k stars 160 forks source link

$tail is bad performance. #1335

Open wvq opened 1 month ago

wvq commented 1 month ago
import typia from 'typia'

interface User {
  id?: number
  name?: string
  avatar?: string
  mobile?: string
}

const user: User = {
  id: 1,
  name: 'Bob',
  avatar: 'https://avatar.com/bob',
  mobile: '12345678901'
}

let stringify = typia.json.createStringify<User>()
performance.mark('test')

for (let i = 0; i < 1e7; i++) {
  stringify(user)
}

let result = performance.measure('test')

console.log(result.duration) // = 3066.775059

The $tail function execution time is positively correlated with length of string because of str[str.length -1]. The longer of the string, the longer time it takes.

export const $tail = (str: string): string =>
  str[str.length - 1] === "," ? str.substring(0, str.length - 1) : str;

// I think it should be 
export const $tail = (str: string, hasLastExpresstion: boolean) => 
  hasLastExpresstion ? str : str.substring(0, -1)

As the generator knows the last prop expression is undefined === input.mobile, just pass second argument undefined !== input.mobile to $tail.

After do this, result.duration reduce to 1733.192805 on my machine.

samchon commented 1 month ago

How about challenging PR from below branch?

https://github.com/samchon/typia/tree/v7.0