blib/lib/DBIx/QuickORM/Manual/Optimizations.pm

filter: Statementstmt 100% 8 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 100% 10 / 10 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/DBIx/QuickORM/Manual/Keys.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/Quickstart.pm »
1 package DBIx::QuickORM::Manual::Optimizations;
2 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 2 our $VERSION = '0.000032';
6  
7 =pod
8  
9 =encoding UTF-8
10  
11 =head1 NAME
12  
13 DBIx::QuickORM::Manual::Optimizations - What is fast, what is slow, and the faster alternatives, with numbers.
14  
15 =head1 DESCRIPTION
16  
17 When something feels slow, find it here. Each section says what the default
18 costs, what is faster, and what the faster form gives up, with timings next
19 to DBIx::Class and raw DBI for scale.
20  
21 Start with L</IF SOMETHING FEELS SLOW>.
22  
23 =head1 THE NUMBERS
24  
25 Collected on 2026-11-28 from commit 1ba80cb5, except the GROUP BY figures,
26 re-measured on 2026-11-29 from commit 8f4dfb70, and the C<insert_many>
27 figures, re-measured on 2026-11-29 from commit ef46fcc1. One machine (16 cores, 32
28 threads), throwaway servers with their data on tmpfs: two MariaDB releases, two
29 MySQL releases, PostgreSQL, and SQLite (the benchmark records which). DBIx::Class
30 ran with InflateColumn::DateTime and a JSON inflator.
31  
32 Times are in microseconds (µs, millionths of a second) unless marked ms
33 (milliseconds, thousandths of a second) or s (seconds). 1 ms is 1,000 µs, and
34 1 s is 1,000 ms. To read a time as a rate, divide one second by it: 15 µs a
35 call is about 67,000 calls a second, and 2 µs a row is 500,000 rows a second.
36  
37 An operation's time is the median of five passes, each pass the median of
38 nine runs. A startup time is the median of five fresh processes after a
39 warmup. A range spans the six databases unless it says otherwise. Reads of
40 many rows are per row. The benchmark lives in the repository's
41 F<agent_scripts/bench> (not in the CPAN distribution).
42  
43 These numbers will grow stale as QuickORM changes. This page may be updated
44 from time to time. Treat them as orders of magnitude, and measure your own
45 code before and after a change.
46  
47 =head1 SCHEMA
48  
49 The examples use PostgreSQL and this schema:
50  
51 =for highlighter language=sql
52  
53 CREATE TABLE users (
54 id SERIAL PRIMARY KEY,
55 name TEXT NOT NULL,
56 email TEXT UNIQUE,
57 prefs JSON,
58 referred_by INTEGER REFERENCES users (id),
59 created TIMESTAMP NOT NULL DEFAULT now()
60 );
61  
62 CREATE TABLE posts (
63 id SERIAL PRIMARY KEY,
64 user_id INTEGER NOT NULL REFERENCES users (id),
65 title TEXT NOT NULL,
66 views INTEGER NOT NULL DEFAULT 0
67 );
68  
69 =head1 IF SOMETHING FEELS SLOW
70  
71 =over 4
72  
73 =item * Reading many rows you do not change
74  
75 Use C<bare> for plain hashrefs, about 2.1x to 2.5x faster than row objects.
76 See L</READING MANY ROWS>.
77  
78 =item * Changing rows you read as C<bare> hashrefs
79  
80 Use the ORM's C<cas_update>, which writes them safely without a canonical
81 copy. See L</READING MANY ROWS>.
82  
83 =item * Reading many rows as row objects you will not write
84  
85 Use C<no_cache> to skip the row cache, about 1.2x faster.
86  
87 =item * Reading a JSON or date field you only display or pass on
88  
89 Use C<raw_field> to skip inflation. See L</READING FIELDS>.
90  
91 =item * Large fields you rarely read
92  
93 Leave them out with C<auto_omit> or C<omit>, and ask for them with C<fields>
94 when you do. See L</LEAVING FIELDS OUT>.
95  
96 =item * A loop of C<find> calls
97  
98 Fetch the rows with one handle and C<-in>. See L</FINDING ROWS>.
99  
100 =item * A loop of C<insert> calls
101  
102 Use C<insert_many>, in void context when you need nothing back. See
103 L</WRITING>.
104  
105 =item * A loop of C<update> calls making the same change
106  
107 Use a handle's C<update>: one UPDATE changes every matching row.
108  
109 =item * A loop of small transactions
110  
111 When the whole loop should commit or roll back together, wrap it in one
112 transaction.
113  
114 =item * Writes got slower after turning on C<debug>
115  
116 Turn it off outside debugging. See L</DEBUG>.
117  
118 =item * A slow start with many tables
119  
120 Scan instead of loading table classes, and turn off C<autotype> when you do
121 not need types. See L</STARTUP>.
122  
123 =back
124  
125 =head1 READING MANY ROWS
126  
127 =for highlighter language=perl
128  
129 my @rows = $orm->handle('posts')->all; # row objects, canonical, in the row cache
130 my @fresh = $orm->handle('posts')->no_cache->all; # row objects, not in the row cache
131 my @data = $orm->handle('posts')->data_only->all; # hashrefs, still in the row cache
132 my @bare = $orm->handle('posts')->bare->all; # hashrefs the row cache never sees
133  
134 my $views = $bare[0]->{views};
135  
136 Fetching 1000 posts and reading one field, per row:
137  
138 =over 4
139  
140 =item * Default row objects: 1.8 to 2.0 µs
141  
142 =item * C<no_cache>: 1.5 to 1.6 µs
143  
144 =item * C<data_only>: 1.0 to 1.3 µs
145  
146 =item * C<bare>: 0.73 to 0.96 µs
147  
148 =item * DBIx::Class objects: 1.7 to 1.9 µs
149  
150 =item * DBIx::Class HashRefInflator: 0.98 to 1.19 µs
151  
152 =item * Raw DBI hashrefs: 0.55 to 0.83 µs
153  
154 =back
155  
156 A handle fetches its rows together. Walking those 1000 one at a time with
157 C<next> costs 2.7 to 2.9 µs a row, against 4.3 to 4.5 µs for DBIx::Class.
158  
159 What each gives up, on a table with a primary key (a table without one never
160 goes through the row cache, and its rows cannot be refreshed or updated one by
161 one):
162  
163 =over 4
164  
165 =item * Default rows
166  
167 Each row goes into the row cache, so objects for that row share the current
168 canonical copy until a write or a changed or narrower read replaces it
169 (L<DBIx::QuickORM::Manual::Caching>). Skipping the cache saved
170 16% to 21% of the default read time.
171  
172 =item * C<no_cache>
173  
174 Rows are full row objects, but not canonical. Writing one needs
175 C<cas_update> or C<< enforce_canon => 0 >>, or a C<refresh> first.
176  
177 =item * C<data_only>
178  
179 Hashrefs, but still in the row cache. It saves building row objects. Each hashref is
180 the cache's own copy, so never change it.
181  
182 =item * C<bare>
183  
184 Hashrefs straight from the fetch: no inflation, no row methods, no cache.
185 The ORM's CRUD operations take a hashref wherever a row is expected
186 (L<DBIx::QuickORM::Manual::RowClasses/HASHREFS>). A C<bare> hashref is not
187 canonical, so write it with the ORM's C<cas_update>, which compares the fields
188 it changes with what the hashref holds and writes only while the database
189 still holds them. It returns the new row data, or undef when a compared field
190 changed since it was read or the row is gone:
191  
192 my ($post) = $orm->handle('posts')->where({id => $post_id})->bare->all;
193 my $saved = $orm->cas_update(posts => $post, {views => $post->{views} + 1});
194  
195 =back
196  
197 =head1 READING FIELDS
198  
199 my $user = $orm->find(users => $id);
200 my $prefs = $user->field('prefs'); # a Perl hash, decoded on every read
201 my $json = $user->raw_field('prefs'); # the stored text
202 my $year = substr($user->raw_field('created'), 0, 4); # no DateTime built
203  
204 A DateTime or UUID field inflates on first read, and the row keeps the
205 inflated value. JSON is decoded again on every read, which is faster than
206 copying decoded data, so changing it cannot change the row. A DateTime is
207 built only when used.
208  
209 Fetching 1000 users and reading one typed field, per row:
210  
211 =over 4
212  
213 =item * JSON with C<field>: 3.4 to 3.9 µs
214  
215 =item * JSON with C<raw_field>: 2.6 to 3.1 µs
216  
217 =item * DBIx::Class JSON: 3.7 to 4.1 µs
218  
219 =item * DateTime year with C<field>: 23 to 24 µs
220  
221 =item * Date text with C<raw_field>: 2.3 to 2.9 µs
222  
223 =item * DBIx::Class DateTime year: 23 to 24 µs
224  
225 =back
226  
227 QuickORM's JSON read took 4% to 8% less time than DBIx::Class's on every
228 database, each reading the field once per row. For a 6 KB document read whole,
229 QuickORM took 33 to 58 µs a row against 62 to 87 µs.
230  
231 Building the DateTime is nearly all of the date cost, for both ORMs. When the
232 stored text is enough, C<raw_field> skips it.
233  
234 =head1 LEAVING FIELDS OUT
235  
236 my $lean = DBIx::QuickORM->new(
237 connect => $connect,
238 auto_omit => {types => ['JSON']}, # leave JSON fields out of default selects
239 );
240  
241 my @names = map { $_->field('name') } $lean->handle('users')->all; # prefs never fetched
242  
243 # asked for up front: no extra query per row
244 my @prefs = map { $_->field('prefs') } $lean->handle('users')->fields([qw/name prefs/])->all;
245  
246 C<auto_omit> leaves fields out by ORM type or database type, on every table
247 with a primary key whose default fields no C<omit>, C<default_fields>, or
248 given C<db_map> sets. It keeps primary, unique, and foreign key fields.
249 C<< omit => {users => ['prefs']} >> leaves out named fields of one table, and
250 C<default_fields> lists what to keep instead. C<omit> refuses primary key
251 fields, and C<default_fields> adds them (L<DBIx::QuickORM/Constructor>).
252  
253 MariaDB reports JSON columns as text, so name their type with C<types> (the
254 benchmark did) or match them with C<db_types>.
255  
256 Fetching 1000 rows and reading a plain field, per row:
257  
258 =over 4
259  
260 =item * Documents with about 6 KB of JSON, default: 3.2 to 5.6 µs, and 25 to 26 µs on MySQL
261  
262 =item * The same with C<auto_omit>: 1.7 to 2.2 µs
263  
264 =item * DBIx::Class, every column: 2.9 to 6.1 µs, and 26 to 27 µs on MySQL
265  
266 =item * DBIx::Class, listing columns: 1.6 to 1.9 µs
267  
268 =item * Users with small JSON, default: 2.1 to 2.6 µs
269  
270 =item * The same with C<auto_omit>: 2.0 to 2.2 µs
271  
272 =back
273  
274 The gain grows with the size of the field left out. MySQL is slow to send
275 large JSON (raw DBI took 25 to 26 µs a row there too), so leaving it out gains
276 most there, about 13x. For small fields it saves 6% to 20% of the time.
277  
278 The cost comes when code reads a field that was left out. On a row object,
279 the first read of it sends a query for that row. A C<bare> or C<data_only>
280 hashref just lacks the key. Either way, name it in C<fields> when you need it.
281 Without that, each row fetches it with its own query:
282  
283 =over 4
284  
285 =item * Small JSON read with C<auto_omit> and no C<fields>: 33 to 46 µs, against 3.4 to 3.9 µs by default
286  
287 =item * Large JSON, the same: 65 to 111 µs, against 33 to 58 µs by default
288  
289 =item * Large JSON with C<fields> asking for it: 35 to 59 µs
290  
291 =back
292  
293 So leave out what is rarely read, and name it in C<fields> on the handles
294 that read it.
295  
296 Leaving fields out also changes what stays canonical. A read that lacks a
297 field the canonical copy holds replaces that copy. So with C<auto_omit> or
298 C<omit>, listing a table replaces the canonical copy of every row object that
299 holds a field the listing left out. For example, insert a row with its JSON,
300 list the table, then update the row: the update croaks, saying the row data is
301 no longer canonical. Fix it with C<refresh> before the write, with
302 C<cas_update>, or by listing every field the row holds in the listing's
303 C<fields>, since C<fields> replaces the default fields
304 (L<DBIx::QuickORM::Manual::Caching/FIELDS LEFT OUT OF A SELECT>). A row's
305 C<canon_status> says why, and with C<debug> which call replaced it
306 (L<DBIx::QuickORM::Manual::Caching/WHY A ROW IS NOT CANONICAL>).
307  
308 =head1 FINDING ROWS
309  
310 my @users = $orm->handle('users')->where({id => {-in => \@ids}})->all; # one query
311  
312 Finding a user by primary key, per find:
313  
314 =over 4
315  
316 =item * C<find>, row not held: 13 to 22 µs
317  
318 =item * C<find>, the canonical copy already holding every field asked for: 4.3 to 4.6 µs, with no query
319  
320 =item * DBIx::Class C<find>: 149 to 167 µs
321  
322 =item * Raw DBI: 3.6 to 12 µs
323  
324 =back
325  
326 Each find that misses the cache sends a query, so a loop of them costs a
327 query per key. One handle with C<-in> fetches every matching row in one
328 query. The rows come back in the database's order, once each, so rebuild the
329 input's order or duplicates yourself if you need them.
330  
331 =head1 FOLLOWING KEYS AND JOINS
332  
333 =over 4
334  
335 =item * Following a post's key to its author: 54 to 91 µs, DBIx::Class 188 to 207 µs
336  
337 =item * Following a user's key back to their 10 posts: 73 to 114 µs, DBIx::Class 201 to 224 µs
338  
339 =item * Joining posts to authors, per row: 14 to 15 µs, DBIx::Class 44 to 46 µs
340  
341 =item * A GROUP BY over 10000 posts into 1000 groups: 0.92 to 6.4 ms, DBIx::Class 1.35 to 7.1 ms
342  
343 =back
344  
345 Reading each C<follow_fk> handle sends a query. In a loop over many rows, a
346 join fetches the matching pairs in one query, and C<left_join> keeps rows with
347 no match (L<DBIx::QuickORM::Manual::Joins>).
348  
349 A grouped read is 1.1x to 1.6x faster than DBIx::Class, closest on MySQL. A
350 handle blesses its aggregate rows directly, and C<field> reads their columns
351 without the inflation methods unless a column has a type. C<bare> on a grouped
352 handle returns hashrefs instead (not measured here):
353  
354 my @per_user = $orm->handle('posts')->group_by('user_id')->fields({user_id => 'user_id', n => [count => '*']})->bare->all;
355  
356 =head1 WRITING
357  
358 # one statement, nothing read back
359 $orm->insert_many(posts => [map { {user_id => $id, title => "Post $_"} } 1 .. 100]);
360  
361 # one UPDATE changes every matching row
362 my $changed = $orm->handle('posts')->where({user_id => $id})->update({views => 0});
363  
364 # one transaction around the loop
365 $orm->txn(sub { $orm->insert(posts => {user_id => $id, title => "Draft $_"}) for 1 .. 10 });
366  
367 Per row:
368  
369 =over 4
370  
371 =item * C<insert>, getting each row back: 31 to 44 µs, DBIx::Class C<create> 99 to 125 µs
372  
373 =item * C<insert_many> of 1000, void context: 3.1 to 7.9 µs, DBIx::Class C<populate> 3.8 to 15 µs
374  
375 =item * C<insert_many> of 1000, rows back: 5.6 to 9.8 µs, DBIx::Class C<populate> 68 to 89 µs
376  
377 =item * C<update> of a fetched row: 39 to 51 µs, DBIx::Class 66 to 99 µs
378  
379 =item * A transaction holding one insert: 59 to 84 µs, DBIx::Class 121 to 146 µs
380  
381 =item * A nested transaction (savepoint) holding one insert: 42 to 63 µs, DBIx::Class 120 to 130 µs
382  
383 =back
384  
385 In void context, C<insert_many> is 1.7x to 2.6x faster than C<populate> on
386 the servers, and a little faster on SQLite (3.1 against 3.8 µs). On the
387 servers it also beats raw DBI executing one prepared C<INSERT> per row in a
388 transaction (9.5 to 13 µs). On SQLite that loop takes 1.0 µs.
389  
390 A handle's C<update> of 1000 rows took 0.18 to 2.5 ms in one statement. At
391 39 to 51 µs a row, updating them one at a time would take about 39 to 51 ms.
392 It returns a count, and drops every canonical copy of the table's rows, since
393 it cannot tell which changed.
394  
395 Where the statement supports C<RETURNING>, an C<insert> that returns a row
396 (without C<as_given>) or a row C<update> reads back the default fields and the
397 fields written, and a row C<update> also the fields the row held. MySQL has no
398 C<RETURNING>, and QuickORM does not use MariaDB's on C<UPDATE>
399 (L<DBIx::QuickORM::Manual::Dialects/RETURNING>), so there a written row holds
400 only its key and other fields load when read. On MySQL, C<insert_many>
401 returns rows only when every row carries its key.
402  
403 A C<count> is one query: 15 to 16 µs on SQLite and MariaDB, 367 to 432 µs on
404 PostgreSQL and MySQL (where raw DBI takes 359 to 424), against 136 to 585 µs
405 for DBIx::Class.
406  
407 =head1 DEBUG
408  
409 my $traced = DBIx::QuickORM->new(connect => $connect, debug => 1); # records which call made a row stale
410  
411 C<< debug => 1 >> makes C<canon_status>, and the croak for writing a row that
412 is no longer canonical, name the call that replaced the row. It is off by
413 default because every public call that can write row data then records its
414 caller. Per operation:
415  
416 =over 4
417  
418 =item * C<find>, row not held: 0.2 to 0.8 µs more
419  
420 =item * C<update> of a fetched row: 0.1 to 4.8 µs more
421  
422 =item * C<insert>, getting the row back: up to 9.8 µs more, within the noise on some databases
423  
424 =back
425  
426 A fetch of many rows costs nothing more per row, unless it replaces canonical
427 copies, each of which gets a note. Turn it on while chasing a
428 stale row, or in development and tests
429 (L<DBIx::QuickORM::Manual::Caching/WHY A ROW IS NOT CANONICAL>).
430  
431 =head1 STARTUP
432  
433 my $quick = DBIx::QuickORM->new(connect => $connect, autotype => undef); # no types loaded, nothing inflated
434  
435 # a later new() in the same process reuses the first scan
436 my $again = DBIx::QuickORM->new(connect => $connect);
437  
438 # after changing tables in a running process
439 my $fresh = DBIx::QuickORM->new(connect => $connect, rescan => 1);
440  
441 Time for a fresh process to load, build, find one row, and read a date and a
442 JSON value, in ms, at 10, 100, and 1000 tables:
443  
444 =over 4
445  
446 =item * Scan, C<< autotype => undef >>: 40 to 52, 45 to 59, 104 to 144
447  
448 =item * Scan with types: 104 to 121, 112 to 125, 181 to 221
449  
450 =item * Table classes: 107 to 124, 123 to 142, 296 to 333
451  
452 =item * DBIx::Class classes, no inflation: 60 to 69, 78 to 85, 381 to 396
453  
454 =item * DBIx::Class classes, inflating dates and JSON: 113 to 125, 142 to 151, 520 to 535
455  
456 =item * DBIx::Class::Schema::Loader: 164 to 264, 508 to 4921, and 6.7 to 74 s (on MySQL one run at 1000 tables did not finish within 8 minutes)
457  
458 =back
459  
460 At 10 tables, in "scan with types", the first query and its two field reads
461 took 58 to 60 ms. That first use also loads DateTime and its formatters. A program that
462 touches no date at startup, not even a date primary key, does not pay it.
463 DBIx::Class's first inflated read took 54 to 58 ms.
464  
465 A scan builds faster than table classes, which are compiled and merged onto
466 the scan. With C<autotype> off, and no C<types> given, nothing is inflated, so
467 nothing loads DateTime. That is most of the gap above, since the measurement
468 reads a date. It also saved 2.3 to 4.3 ms of build at 10 tables, and 8.8 to
469 14 ms at 1000. The cost is that fields
470 come back as stored (L<DBIx::QuickORM::Manual::Types>).
471  
472 The first scan of a database is kept for the rest of the process, so building
473 another ORM for the same database and session (after a lost connection, say)
474 does not scan again. In-memory SQLite and DuckDB databases, and PostgreSQL
475 sessions with temporary tables, always scan. A
476 rebuild and one find took 0.25 ms on SQLite, 0.41 to 0.45 ms on MariaDB and
477 MySQL, and 2.0 ms on PostgreSQL. DBIx::Class, cloning its compiled classes,
478 took 0.43, 0.54 to 0.56, and 2.2 ms. With C<rescan> the scan runs again: 0.47
479 ms, 0.82 to 2.2 ms, and 5.6 ms. Pass C<rescan> only when tables changed.
480  
481 =head1 SEE ALSO
482  
483 L<DBIx::QuickORM::Manual::Caching> for what the row cache does,
484 L<DBIx::QuickORM::Manual::RowClasses> for hashrefs and row classes,
485 L<DBIx::QuickORM::Manual::BulkInsert> for C<insert_many>, and
486 L<DBIx::QuickORM::Manual::DBIC> for the same tasks side by side with
487 DBIx::Class.
488  
489 =cut
490  
491 2 1;
492  
493 __END__
« blib/lib/DBIx/QuickORM/Manual/Keys.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/Quickstart.pm »