@@ -2,36 +2,37 @@ import {readFileSync} from 'node:fs';
22import path from 'node:path' ;
33import process from 'node:process' ;
44import { fileURLToPath } from 'node:url' ;
5+ import { parseArgs } from 'node:util' ;
56
67import { Bench } from 'tinybench' ;
78import { grammar } from '@ohm-js/compiler/compat' ;
89
910const __dirname = path . dirname ( fileURLToPath ( import . meta. url ) ) ;
1011
11- const ohmSource = readFileSync ( path . join ( __dirname , 'json.ohm' ) , 'utf-8' ) ;
12- const json = grammar ( ohmSource ) ;
12+ const json = grammar ( readFileSync ( path . join ( __dirname , 'json.ohm' ) , 'utf-8' ) ) ;
13+ const fastjson = grammar ( readFileSync ( path . join ( __dirname , 'fastjson.ohm' ) , 'utf-8' ) ) ;
1314
1415// The benchmark file assigns a JSON string to `self.sample`.
1516// Evaluate it to extract the actual JSON.
1617const jsSource = readFileSync ( path . join ( __dirname , 'test/data/1K_json.js' ) , 'utf-8' ) ;
1718const self : Record < string , string > = { } ;
1819new Function ( 'self' , jsSource ) ( self ) ;
19- const input = self . sample ;
20+ let input = self . sample ;
2021
21- // Sanity check: verify JSON.parse and our grammar both accept it.
22- JSON . parse ( input ) ;
23- json . match ( input ) . use ( r => {
24- if ( ! r . succeeded ( ) ) throw new Error ( 'Match failed' ) ;
22+ const { values} = parseArgs ( {
23+ options : { 'small-size' : { type : 'boolean' , default : false } } ,
2524} ) ;
26- console . error ( `Input: 1K_json.js ( ${ ( input . length / 1024 ) . toFixed ( 0 ) } KB)` ) ;
25+ const smallSize = values [ 'small-size' ] ;
2726
28- const smallSize = process . argv . includes ( '--small-size' ) ;
29- const iterations = smallSize ? 1 : 10 ;
27+ // For 'small-size' just test some random JSON.
28+ if ( smallSize ) {
29+ input = '{ "extends": "../tsconfig.base.json", "include": ["*.ts", "test/**/*.ts"] }' ;
30+ }
3031
3132const bench = new Bench ( {
32- iterations,
33+ iterations : smallSize ? 1 : 10 ,
3334 time : 0 ,
34- warmup : true ,
35+ warmup : ! smallSize ,
3536} ) ;
3637
3738const opts = {
@@ -40,21 +41,9 @@ const opts = {
4041 } ,
4142} ;
4243
43- bench . add (
44- 'ohm (wasm)' ,
45- ( ) => {
46- json . match ( input ) . use ( r => r . succeeded ( ) ) ;
47- } ,
48- opts
49- ) ;
50-
51- bench . add (
52- 'JSON.parse' ,
53- ( ) => {
54- JSON . parse ( input ) ;
55- } ,
56- opts
57- ) ;
44+ bench . add ( 'JSON' , ( ) => json . match ( input ) . use ( r => r . succeeded ( ) ) , opts ) ;
45+ bench . add ( 'FastJSON' , ( ) => fastjson . match ( input ) . use ( r => r . succeeded ( ) ) , opts ) ;
46+ bench . add ( 'JSON.parse' , ( ) => JSON . parse ( input ) , opts ) ;
5847
5948( async ( ) => {
6049 await bench . run ( ) ;
0 commit comments