测试中psycopg2服务器端游标为何比客户端游标慢?
PostgreSQL客户端游标与服务器端游标性能差异分析问题
测试背景
我正在分析PostgreSQL数据库批量加载与流式加载的性能差异:批量方案采用psycopg2客户端游标,流式方案采用itersize为20000的服务器端游标,测试表约含60万行数据。
服务器端游标测试代码
with psycopg2.connect(dbname=.., host=.., port=.., user=.., password=..) as conn: cursor = conn.cursor("server_side", cursor_factory=psycopg2.extras.RealDictCursor) cursor.itersize = 20_000 cursor.execute("select * from schema.large_table") for i, row in enumerate(cursor): if i % 1000 == 0: print(f"Row number {i}") if i == 10_000: break
预期行为:该方案会先将20000行数据拉取到客户端,迭代至第10000行时停止。
客户端游标测试代码
with psycopg2.connect(dbname=.., host=.., port=.., user=.., password=..) as conn: cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cursor.execute("select * from schema.large_table") for i, row in enumerate(cursor): if i % 1000 == 0: print(f"Row number {i}") if i == 10_000: break
预期行为:该方案会先拉取全表60万行数据,再迭代至第10000行停止,因传输数据更多应更慢。
测试结果与疑问
实际测试中,客户端方案耗时65秒,服务器端方案耗时约619秒(慢10倍),且客户端进程内存占用更高,两者处理行数一致。
编辑补充:按建议修正代码(将enumerate(cursor.fetchone())改为enumerate(cursor))后,客户端游标耗时约为服务器端的4.5倍,内存占用仍更高。请问最初为何服务器端游标性能更差?
内容的提问来源于stack exchange,提问作者it's-yer-boy-chet
相关产品推荐
相关产品推荐

