PostgreSQL numeric类型上的算术运算比整数类型或者浮点数类型要慢很多

准备两个function,一个使用integer计算,一个使用numeric计算

使用Integer计算:

create function compute_integer()returns integer as $$
declare
   num integer:=0;
begin
   for i in 1..10000 loop
      num=num+i;
   end loop;
   return num;
end;
$$language plpgsql;

使用nemeric计算:

create function compute_numeric)returns numeric as $$
declare
   num numeric:=0.0;
begin
   for i in 1..10000 loop
      num=num+i;
   end loop;
   return num;
end;
$$language plpgsql;

观察运算结果:

1. integer

postgres=# explain analyze select compute_integer();
                                     QUERY PLAN                                     
------------------------------------------------------------------------------------
 Result  (cost=0.00..0.26 rows=1 width=0) (actual time=6.816..6.817 rows=1 loops=1)
 Total runtime: 6.829 ms
(2 rows)

2. numeric

postgres=# explain analyze select compute_numeric();
                                      QUERY PLAN                                      
--------------------------------------------------------------------------------------
 Result  (cost=0.00..0.26 rows=1 width=0) (actual time=14.011..14.012 rows=1 loops=1)
 Total runtime: 14.029 ms
(2 rows)

后者的计算速度还是慢一些的。


你可能感兴趣的:(PostgreSQL,优化)