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

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

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

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

测试结果以下:数据库

Rust 存储过程:swift

test_sql_speed: 26.810285862s

Go 链接数据库查询:bash

32.746561715s

Go 语言只创建一次链接。性能

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

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

此次,Rust 存储过程:orm

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 秒。

相关文章
相关标签/搜索