-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark.js
More file actions
232 lines (191 loc) · 6.33 KB
/
benchmark.js
File metadata and controls
232 lines (191 loc) · 6.33 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import "reflect-metadata";
import { performance } from "perf_hooks";
import TypeORMBenchmark from "./orms/typeorm.js";
import SequelizeBenchmark from "./orms/sequelize.js";
import PrismaBenchmark from "./orms/prisma.js";
import ObjectionBenchmark from "./orms/objection.js";
// Generate test data
function generateTestData(count = 1000, iteration = 0) {
const users = [];
const timestamp = Date.now();
const randomSuffix = Math.random().toString(36).substring(2, 15);
for (let i = 0; i < count; i++) {
users.push({
email: `user${i}_${timestamp}_${iteration}_${randomSuffix}_${i}@example.com`,
name: `User ${i}`,
age: Math.floor(Math.random() * 50) + 18,
isActive: Math.random() > 0.3,
});
}
return users;
}
// Calculate statistics
function calculateStats(times) {
const sorted = times.sort((a, b) => a - b);
const sum = times.reduce((a, b) => a + b, 0);
const avg = sum / times.length;
const min = sorted[0];
const max = sorted[sorted.length - 1];
const median = sorted[Math.floor(sorted.length / 2)];
return { avg, min, max, median };
}
// Format time in milliseconds
function formatTime(ms) {
return `${ms.toFixed(2)}ms`;
}
// Print results table
function printResults(results) {
console.log("\n" + "=".repeat(80));
console.log("ORM BENCHMARKING RESULTS");
console.log("=".repeat(80));
const operations = [
"bulkInsert",
"individualInsert",
"selectAll",
"selectWithWhere",
"update",
"delete",
"complexQuery",
];
const orms = ["TypeORM", "Sequelize", "Prisma", "Objection.js"];
operations.forEach((operation) => {
console.log(`\n${operation.toUpperCase()}:`);
console.log("-".repeat(40));
const operationResults = orms
.map((orm) => ({
orm,
stats:
results[orm] && results[orm][operation]
? results[orm][operation]
: null,
}))
.filter((result) => result.stats !== null);
if (operationResults.length === 0) {
console.log("❌ No results available for this operation");
return;
}
// Sort by average time (fastest first)
operationResults.sort((a, b) => a.stats.avg - b.stats.avg);
operationResults.forEach((result, index) => {
const { orm, stats } = result;
const rank =
index === 0 ? "🥇" : index === 1 ? "🥈" : index === 2 ? "🥉" : " ";
console.log(
`${rank} ${orm.padEnd(12)} | ` +
`Avg: ${formatTime(stats.avg).padEnd(10)} | ` +
`Min: ${formatTime(stats.min).padEnd(10)} | ` +
`Max: ${formatTime(stats.max).padEnd(10)} | ` +
`Median: ${formatTime(stats.median)}`
);
});
});
console.log("\n" + "=".repeat(80));
}
// Run benchmark for a single ORM
async function runBenchmark(ormClass, ormName, testData, iterations = 5) {
console.log(`\n🧪 Testing ${ormName}...`);
const orm = new ormClass();
const results = {
bulkInsert: [],
individualInsert: [],
selectAll: [],
selectWithWhere: [],
update: [],
delete: [],
complexQuery: [],
};
try {
await orm.initialize();
for (let i = 0; i < iterations; i++) {
console.log(` Iteration ${i + 1}/${iterations}`);
// Generate fresh test data for each iteration
const iterationTestData = generateTestData(1000, i);
const individualTestData = generateTestData(100, i);
// Clear data before each iteration
await orm.clearData();
try {
// Bulk Insert
const bulkTime = await orm.bulkInsert(iterationTestData);
results.bulkInsert.push(bulkTime);
// Individual Insert
const individualTime = await orm.individualInsert(individualTestData);
results.individualInsert.push(individualTime);
} catch (error) {
console.error(` Error in iteration ${i + 1}:`, error.message);
throw error;
}
// Select All
const selectAllTime = await orm.selectAll();
results.selectAll.push(selectAllTime);
// Select with Where
const selectWhereTime = await orm.selectWithWhere();
results.selectWithWhere.push(selectWhereTime);
// Update
const updateTime = await orm.update();
results.update.push(updateTime);
// Complex Query
const complexTime = await orm.complexQuery();
results.complexQuery.push(complexTime);
// Delete
const deleteTime = await orm.delete();
results.delete.push(deleteTime);
}
// Calculate statistics for each operation
const stats = {};
Object.keys(results).forEach((operation) => {
stats[operation] = calculateStats(results[operation]);
});
return stats;
} finally {
await orm.cleanup();
}
}
// Main benchmark function
async function runAllBenchmarks() {
console.log("🚀 Starting ORM Benchmarking Experiment");
console.log("Node.js version:", process.version);
console.log("Platform:", process.platform);
console.log("Architecture:", process.arch);
const testData = generateTestData(1000);
const iterations = 5;
console.log(`\n📊 Test Configuration:`);
console.log(` - Test data: ${testData.length} users`);
console.log(` - Iterations: ${iterations}`);
console.log(` - Database: SQLite`);
const startTime = performance.now();
const results = {};
// Run benchmarks for each ORM
const benchmarks = [
{ class: TypeORMBenchmark, name: "TypeORM" },
{ class: SequelizeBenchmark, name: "Sequelize" },
{ class: PrismaBenchmark, name: "Prisma" },
{ class: ObjectionBenchmark, name: "Objection.js" },
];
for (const benchmark of benchmarks) {
try {
results[benchmark.name] = await runBenchmark(
benchmark.class,
benchmark.name,
testData,
iterations
);
} catch (error) {
console.error(`❌ Error testing ${benchmark.name}:`, error.message);
results[benchmark.name] = null;
}
}
const totalTime = performance.now() - startTime;
// Print results
printResults(results);
console.log(`\n⏱️ Total benchmark time: ${formatTime(totalTime)}`);
console.log("\n✅ Benchmarking completed!");
}
// Handle errors and run benchmarks
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled Rejection at:", promise, "reason:", reason);
process.exit(1);
});
runAllBenchmarks().catch((error) => {
console.error("❌ Benchmark failed:", error);
process.exit(1);
});