Last active
March 20, 2019 14:36
-
-
Save rkaw92/3fca214a0c83834dbca9e10bdd891f12 to your computer and use it in GitHub Desktop.
Node.js pg first query takes longer than subsequent queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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(); |
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
My results show that the first query indeed takes longer: