I tested four procedure languages for PostgreSQL 9.2: plpgsql, plperl, plpython2u, plperl and plv8 with Fibonacci numbers function. And V8 was the best!
Functions:
postgres=# \sf jsfib
CREATE OR REPLACE FUNCTION public.jsfib(a integer)
RETURNS integer
LANGUAGE plv8
AS $function$
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2)
}
return fib(a)
$function$
postgres=# \sf perlfib(integer)
CREATE OR REPLACE FUNCTION public.perlfib(integer)
RETURNS integer
LANGUAGE plperl
AS $function$
sub fib {
my ($n) = @_;
if ($n < 2) {
return $n;
}
return fib($n - 1) + fib($n - 2);
}
return fib($_[0]);
$function$
postgres=# \sf psqlfib
CREATE OR REPLACE FUNCTION public.psqlfib(n integer)
RETURNS integer
LANGUAGE plpgsql
IMMUTABLE STRICT
AS $function$
BEGIN
IF n < 2 THEN
RETURN n ;
END IF ;
RETURN psqlfib (n - 1 ) + psqlfib (n - 2 ) ;
END;
$function$
postgres=# \sf pythonfib
CREATE OR REPLACE FUNCTION public.pythonfib(a integer)
RETURNS integer
LANGUAGE plpython2u
AS $function$
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
return fib(a)
$function$
postgres=# EXPLAIN ANALYZE SELECT n , jsfib(n) FROM generate_series ( 0 , 30 , 5 ) as n ;
Total runtime: 26.517 ms
postgres=# EXPLAIN ANALYZE SELECT n , pythonfib(n) FROM generate_series ( 0 , 30 , 5 ) as n ;
Total runtime: 607.102 ms
postgres=# EXPLAIN ANALYZE SELECT n , perlfib(n) FROM generate_series ( 0 , 30 , 5 ) as n ;
Total runtime: 1530.294 ms
postgres=# EXPLAIN ANALYZE SELECT n , psqlfib(n) FROM generate_series ( 0 , 30 , 5 ) as n ;
Total runtime: 34838.510 ms
Functions:
postgres=# \sf jsfib
CREATE OR REPLACE FUNCTION public.jsfib(a integer)
RETURNS integer
LANGUAGE plv8
AS $function$
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2)
}
return fib(a)
$function$
postgres=# \sf perlfib(integer)
CREATE OR REPLACE FUNCTION public.perlfib(integer)
RETURNS integer
LANGUAGE plperl
AS $function$
sub fib {
my ($n) = @_;
if ($n < 2) {
return $n;
}
return fib($n - 1) + fib($n - 2);
}
return fib($_[0]);
$function$
postgres=# \sf psqlfib
CREATE OR REPLACE FUNCTION public.psqlfib(n integer)
RETURNS integer
LANGUAGE plpgsql
IMMUTABLE STRICT
AS $function$
BEGIN
IF n < 2 THEN
RETURN n ;
END IF ;
RETURN psqlfib (n - 1 ) + psqlfib (n - 2 ) ;
END;
$function$
postgres=# \sf pythonfib
CREATE OR REPLACE FUNCTION public.pythonfib(a integer)
RETURNS integer
LANGUAGE plpython2u
AS $function$
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
return fib(a)
$function$
postgres=# EXPLAIN ANALYZE SELECT n , jsfib(n) FROM generate_series ( 0 , 30 , 5 ) as n ;
postgres=# EXPLAIN ANALYZE SELECT n , pythonfib(n) FROM generate_series ( 0 , 30 , 5 ) as n ;
Total runtime: 607.102 ms
postgres=# EXPLAIN ANALYZE SELECT n , perlfib(n) FROM generate_series ( 0 , 30 , 5 ) as n ;
Total runtime: 1530.294 ms
postgres=# EXPLAIN ANALYZE SELECT n , psqlfib(n) FROM generate_series ( 0 , 30 , 5 ) as n ;
Total runtime: 34838.510 ms
No comments:
Post a Comment