PostgreSQL 数据库内外查询速度比较

原创
2018/11/06 11:11
阅读数 3K

数据库内使用 Rust 编写存储过程,使用 pgxr 程序库;

数据库外使用 Go 语言,使用 pgx 连接数据库进行查询;

逻辑都是查询某个表的字段列表,循环执行10000次;

测试结果如下:

Rust 存储过程:

test_sql_speed: 26.810285862s

Go 连接数据库查询:

32.746561715s

Go 语言只建立一次连接。

看来复用连接的话开销很小的嘛,一次只需要花费 0.5 毫秒左右。

然后,又测试了最简单的 SQL 查询:SELECT 1,同样也是 10000 次;

这次,Rust 存储过程:

test_sql_speed: 67.651917ms

Go 连接数据库查询:

1.261617769s

数据库内查询那是相当快的,这样算来每次处理连接的耗时大概在 0.1 毫秒左右。

源代码如下:

Rust

#[no_mangle]
pub extern "C" fn test_sql_speed(_fcinfo: FunctionCallInfo) -> Datum
{
    let sys_time = SystemTime::now();
    for _ in 1..10000 {
        let _i = query_for_int("select 1");
    }
    let difference = SystemTime::now().duration_since(sys_time)
                         .expect("SystemTime::duration_since failed");
    eprintln!("test_sql_speed: {:?}", difference);
    PG_RETURN_I32(1)
}

Go

func main() {
	db := openDbConnection()
	start := time.Now()
	i := 0
	for i = 1; i <= 10000; i++ {
		db.Query(`SELECT 1`)
	}
	t := time.Now()
	elapsed := t.Sub(start)
	fmt.Printf("%v\n", elapsed)
}

后来发现用于查询表字段的方法效率不行,是从 information_schema 这个 ANSI 标准目录里去查的,后来看了一些资料,改成从 pg_catalog 这个原生目录去查,结果性能有了大幅提升。

Rust 里查询一万次只用了 1 秒,Go 里查询一万次用了 3 秒。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
1 收藏
0
分享
返回顶部
顶部