zoukankan      html  css  js  c++  java
  • postgresql 的 prepare 探索之一

    os:centos 7.4
    postgresql:10.4

    PREPARE — 为执行准备一个语句,类似于oracle 的绑定变量,可以直接使用相同的执行计划,没有硬解析的代价。

    应用场景为:在一个会话要执行大量类似语句时,预备语句可能会有最大性能优势。
    如果该语句很复杂(难于规划或重写),例如,如果查询涉及很多表的连接或者要求应用多个规则,性能差异将会特别明显。
    如果语句相对比较容易规划和重写,但是执行起来开销相对较大,那么预备语句的性能优势就不那么显著了。

    不使用prepare

    $ psql
    psql (10.4)
    Type "help" for help.
    
    postgres=# create table test01(id integer, val text); 
    CREATE TABLE
    postgres=# 	iming
    Timing is on.
    postgres=# DO LANGUAGE plpgsql $$ 
    DECLARE 
       v_c record;
    BEGIN
       for v_c in 
          select id
    	    from generate_series(1,500000) as id
       loop
          execute 'insert into test01 values('||v_c.id||',repeat( chr(int4(random()*26)+65),1000))';
       end loop;
    end;
    $$;
    
    DO
    Time: 28109.551 ms (00:28.110)
    
    

    使用prepare

    $ psql
    psql (10.4)
    Type "help" for help.
    
    postgres=# drop table test01;
    DROP TABLE
    postgres=# create table test01(id integer, val text); 
    CREATE TABLE
    postgres=# 	iming
    Timing is on.
    postgres=# DO LANGUAGE plpgsql $$ 
    DECLARE 
       v_c record;
    BEGIN
       deallocate prepare insert_test01_plan;
       execute 'prepare insert_test01_plan as insert into test01 VALUES($1, $2)';
       for v_c in 
          select id
    	    from generate_series(1,500000) as id
       loop
          execute 'execute insert_test01_plan('||v_c.id||',repeat( chr(int4(random()*26)+65),1000)) ';
       end loop;
    end;
    $$;
    
    DO
    Time: 27015.875 ms (00:27.016)
    
    

    1、Prepared语句只在session的整个生命周期中存在,一旦session结束,Prepared语句也不存在了。如果下次再使用需重新创建。
    2、Prepared语句不能在多个并发的client中共有。
    3、prepared语句可以通过DEALLOCATE命令清除。
    4、当前session的prepared语句:pg_prepared_statements

    任何事物都有其两面性,prepare在提高性能的同时,也有可能成为性能的杀手。

    参考:
    http://postgres.cn/docs/10/sql-prepare.html#SQL-PREPARE-EXAMPLES

  • 相关阅读:
    Git 简要教程
    SDK更新失败问题解决
    常用安卓操作
    MongoDB本地安装与启用(windows 7/10)
    windows 快捷键收集
    windows 常用命令
    Lambda Expression Introduction
    对 load_breast_cancer 进行 SVM 分类
    Support Vector Machine
    使用 ID3 对 Titanic 进行决策树分类
  • 原文地址:https://www.cnblogs.com/ctypyb2002/p/9792893.html
Copyright © 2011-2022 走看看