Skip to content

Instantly share code, notes, and snippets.

@rkaw92
Last active March 20, 2019 14:36
Show Gist options
  • Save rkaw92/3fca214a0c83834dbca9e10bdd891f12 to your computer and use it in GitHub Desktop.
Save rkaw92/3fca214a0c83834dbca9e10bdd891f12 to your computer and use it in GitHub Desktop.
Node.js pg first query takes longer than subsequent queries
'use strict';
const pg = require('pg');
const PG_URL = process.env.PG_URL || 'postgres://postgres:postgres@127.0.0.1/postgres';
const ITERATIONS = Number(process.env.ITERATIONS || 10);
const VARIANT = Number(process.env.VARIANT || 0);
async function benchmarkPg() {
const client = new pg.Client({
connectionString: PG_URL
});
await client.connect();
const times = new Array(ITERATIONS);
let rows;
for (let i = 0; i < ITERATIONS; i += 1) {
const timeStart = process.hrtime();
if ((i + VARIANT) % 2 === 0) {
rows = (await client.query('SELECT 1')).rows;
} else {
rows = (await client.query("SELECT * FROM (VALUES ('val1', 'val2')) t")).rows;
}
const timeEnd = process.hrtime(timeStart);
times[i] = timeEnd;
}
console.log('ran %d queries; times:', ITERATIONS);
for (let i = 0; i < ITERATIONS; i += 1) {
const timeEnd = times[i];
console.log('%d: %f ms', i, (timeEnd[0] * 1000 + timeEnd[1]/1000000));
}
}
benchmarkPg();
@rkaw92
Copy link
Author

rkaw92 commented Mar 20, 2019

My results show that the first query indeed takes longer:

ran 10 queries; times:
0: 2.069616 ms
1: 0.542416 ms
2: 0.382777 ms
3: 0.415688 ms
4: 0.371435 ms
5: 0.361968 ms
6: 0.321762 ms
7: 0.302884 ms
8: 0.275773 ms
9: 0.219883 ms

@rkaw92
Copy link
Author

rkaw92 commented Mar 20, 2019

Adding this line right after .connect() changes nothing, which indicates it's a connection initialization or query initialization effect:

await new Promise(function(resolve) { setTimeout(resolve, 500); });

(the .connect is not resolving prematurely, that is)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment