-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-person-benchmark.js
More file actions
209 lines (179 loc) Β· 7.02 KB
/
Copy pathsimple-person-benchmark.js
File metadata and controls
209 lines (179 loc) Β· 7.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
/**
* Simple Person Validation Benchmark
*
* This benchmark tests the absolute minimum validation scenario:
* - Single object with one field
* - Only "required" rule applied
* - Tests pure validation library overhead
*
* This represents the baseline performance all libraries should achieve
* for the simplest possible validation case.
*/
const { Bench } = require("tinybench");
const { z } = require("zod");
const Joi = require("joi");
const { Validator, required } = require("validant");
const yup = require("yup");
const { string, object, assert } = require("superstruct");
const FastestValidator = require("fastest-validator");
console.log("π Simple Person Validation Benchmark");
console.log("=".repeat(60));
console.log(`Node.js: ${process.version}`);
console.log("Testing minimal validation: person { name: string (required) }\n");
// =============================================================================
// TEST DATA
// =============================================================================
const validPersonData = {
name: "John Doe"
};
const invalidPersonData = {
name: ""
};
// =============================================================================
// VALIDATION SCHEMAS
// =============================================================================
const schemas = {
zod: z.object({
name: z.string().min(1)
}),
joi: Joi.object({
name: Joi.string().required()
}),
validant: {
name: [required('Name is required')]
},
yup: yup.object({
name: yup.string().required()
}),
superstruct: object({
name: string()
}),
"fastest-validator": new FastestValidator().compile({
name: { type: "string", empty: false }
})
};
// =============================================================================
// VALIDATION FUNCTION
// =============================================================================
function validateWith(library, schema, data) {
try {
switch (library) {
case "zod":
return schema.parse(data);
case "joi":
const result = schema.validate(data);
if (result.error) throw result.error;
return result.value;
case "validant":
const validator = new Validator();
const validantResult = validator.validate(data, schema);
if (!validantResult.isValid) throw new Error(validantResult.message);
return data;
case "yup":
return schema.validateSync(data);
case "superstruct":
assert(data, schema);
return data;
case "fastest-validator":
const validationCheck = schema(data);
if (validationCheck !== true) throw new Error("Validation failed");
return data;
default:
throw new Error(`Unknown library: ${library}`);
}
} catch (error) {
return null;
}
}
// =============================================================================
// BENCHMARK RUNNER
// =============================================================================
async function runBenchmark(testName, data, description, expectFailure = false) {
console.log(`\nπ― ${testName}`);
console.log(`${description}`);
console.log("β".repeat(60));
const bench = new Bench({ time: 2000 });
const libraries = ["fastest-validator", "zod", "joi", "validant", "yup", "superstruct"];
console.log("Testing library compatibility...");
const workingLibraries = [];
for (const lib of libraries) {
if (schemas[lib]) {
try {
const result = validateWith(lib, schemas[lib], data);
if (!expectFailure && result !== null) {
workingLibraries.push(lib);
console.log(`β
${lib} - validation passed`);
} else if (expectFailure && result === null) {
workingLibraries.push(lib);
console.log(`β
${lib} - validation failed as expected`);
} else if (expectFailure && result !== null) {
console.log(`β ${lib} - should have failed but passed`);
} else {
console.log(`β ${lib} - unexpected result`);
}
} catch (error) {
if (expectFailure) {
workingLibraries.push(lib);
console.log(`β
${lib} - threw error as expected`);
} else {
console.log(`β ${lib} - error: ${error.message}`);
}
}
} else {
console.log(`β ${lib} - no schema defined`);
}
}
if (workingLibraries.length === 0) {
console.log("β No working libraries found");
return;
}
workingLibraries.forEach(lib => {
bench.add(lib, () => {
validateWith(lib, schemas[lib], data);
});
});
await bench.run();
console.log("\nπ Performance Results:");
bench.tasks
.sort((a, b) => b.result.hz - a.result.hz)
.forEach((task, index) => {
const opsPerSec = Math.round(task.result.hz).toLocaleString();
const rme = task.result.rme.toFixed(2);
const emoji = index === 0 ? "π₯" : index === 1 ? "π₯" : index === 2 ? "π₯" : " ";
console.log(`${emoji} ${task.name.padEnd(18)}: ${opsPerSec.padStart(12)} ops/sec Β±${rme}%`);
});
// Calculate relative performance
const fastest = bench.tasks.sort((a, b) => b.result.hz - a.result.hz)[0];
const slowest = bench.tasks.sort((a, b) => a.result.hz - b.result.hz)[0];
const speedDifference = (fastest.result.hz / slowest.result.hz).toFixed(1);
console.log(`\nπ Winner: ${fastest.name} (${speedDifference}x faster than slowest)`);
}
// =============================================================================
// MAIN EXECUTION
// =============================================================================
(async () => {
try {
await runBenchmark(
"Valid Person Data",
validPersonData,
"Testing successful validation of: { name: 'John Doe' }"
);
await runBenchmark(
"Invalid Person Data",
invalidPersonData,
"Testing validation failure of: { name: '' }",
true
);
console.log("\n" + "=".repeat(60));
console.log("π― Simple Person Benchmark Complete!");
console.log("\nKey Insights:");
console.log("β’ This represents the absolute minimum validation overhead");
console.log("β’ Performance differences show library baseline costs");
console.log("β’ Real-world scenarios will have additional complexity");
console.log("β’ Consider this the 'speed of light' for each library");
console.log("=".repeat(60));
} catch (error) {
console.error("β Benchmark failed:", error);
process.exit(1);
}
})();