數據庫內使用 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 秒。