Node.js查询性能测试异常:后执行查询始终更快的问题排查
PostgreSQL查询性能测试异常:第二个查询总是比第一个更快
我编写了一个简单的Node.js程序用于测试PostgreSQL查询性能,但遇到异常:当循环执行查询数组时,第二个查询总是比第一个更快。例如数组为[A,B]时B更快,改为[B,A]时A更快,但单独执行任一查询或在psql中执行时,两者性能几乎一致。
相关代码
index.js
const { Client } = require('pg'); const queryPref = require('./src/QueryPref'); require('dotenv').config(); (async ()=> await queryPref())();
queryPref.js
const { Client } = require('pg'); const queries = [ { 'queryStr': 'SELECT * FROM tabluno where user_name = $1', 'options': ['08544f75d007ae439925bb21fe48c64c'], }, { 'queryStr': 'SELECT * FROM tabluno2 where user_name = $1', 'options': ['f67a10e60fde706bb6c5948374b385e5'], }, ] function initClient() { console.log('opening a new connection'); const client = new Client({ user: 'postgres', host: 'localhost', database: 'indexing-is-really-hard', password: process.env.DB_PASSWORD, port: 5432 // default port for postgres }); return client; } async function queryPref() { for(const query of queries) { let pool = new Client({ user: 'postgres', host: 'localhost', database: 'indexing-is-really-hard', password: process.env.DB_PASSWORD, port: 5432, // default port for postgres }); await pool.connect(); await pool.query('SELECT 1'); let avg = 0; for(let i = 0; i < 1000; i++) { const start = performance.now(); await pool.query(query.queryStr, query.options) const end = performance.now(); avg += end - start; } avg /= 1000; console.log(`${query.queryStr} took an avg of ${avg.toFixed(3)}ms`) pool.end(); pool = null; } } module.exports = queryPref;
已尝试的解决方法
- 为每个查询初始化新的Client,无效果
- 使用连接池、多次执行取平均值,问题依旧
测试结果对比
- Node.js程序测试结果:第二个查询平均耗时明显低于第一个
- psql测试结果:两个查询的平均耗时几乎一致
内容的提问来源于stack exchange,提问作者Hossam Abd Elmenem
相关产品推荐
相关产品推荐

