Different queries result in big difference in performance I have 2 similar functions, different way result in big diff in performance.

The PostgreSQL version: 9.2.1.

Function 1

create or replace function func_1()  returns text  as
$$
declare
   v_i integer;  
   v_md5 varchar; 
begin
   for v_i in 1..1000000 loop
       v_md5:='a'|| v_i::character varying;
   end loop;  
   return 'ok';
end;
$$
language plpgsql;


Function 2

create or replace function func_select()  returns text  as
$$
declare
   v_i integer;  
   v_md5 varchar; 
begin
   for v_i in 1..1000000 loop
      select 'a'|| v_i::character varying into  v_md5;
   end loop;
   return 'ok';
end;
$$
language plpgsql;


Function Timings

francs=&gt; \timing
Timing is on.
francs=&gt; select func_1();
 func_1 
--------
 ok
(1 row)

Time: 1467.231 ms
francs=&gt; select func_1();
 func_1 
--------
 ok
(1 row)

Time: 1383.424 ms
francs=&gt; select func_select();
 func_select 
-------------
 ok
(1 row)

Time: 22176.600 ms
francs=&gt; select func_select();
 func_select 
-------------
 ok
(1 row)

Time: 23265.755 ms


From the above, function func_1() only takes about 1383 ms, but function func_select() takes about  23265 ms, anybody can explain this?
The use of the pure SQL statement in the second loop makes the database engine compile the whole select 'a'|| v_i::character varying into  v_md5; on each loop iteration before evaluating it whereas the variable assignment is parsed easily into low level instructions once.