Re: Speeding up loops in pl/pgsql function - Mailing list pgsql-performance

From Jochen Erwied
Subject Re: Speeding up loops in pl/pgsql function
Date
Msg-id 589023449.20110526104655@erwied.eu
Whole thread Raw
In response to Re: Speeding up loops in pl/pgsql function  ("Reuven M. Lerner" <reuven@lerner.co.il>)
List pgsql-performance
Thursday, May 26, 2011, 12:26:17 AM you wrote:

> Here you go... it looked nicer before I started to make optimizations;
> I've gotten it to run about 2x as fast as the previous version, but now
> I'm sorta stuck, looking for further optimizations, including possible
> use of builtin functions.

I've got only a 9.0.4 to play with, and bytea's are passed as an
hexadecimal string, so I resorted to writing the function with TEXT as
parameters, but maybe the following helps a bit, avoiding a few IMHO
useless string/int-operations:

CREATE OR REPLACE FUNCTION translate_octals_into_decimals(bytea_string text) RETURNS text AS $$
DECLARE
   bytea_string_length INTEGER := length(bytea_string);
   translated_string_array BYTEA[];

   output_number INTEGER := 0;
   num1 INTEGER;
   num2 INTEGER;
   num3 INTEGER;
   npos INTEGER;
   nlen INTEGER;
BEGIN
   RAISE NOTICE '[translate_octals_into_decimals] start at %, string of
length %', clock_timestamp(), pg_size_pretty(length(bytea_string));

   npos := 1;
   FOR i IN 1..bytea_string_length BY 3 LOOP
     num1 := substring(bytea_string from i for 1);
     num2 := substring(bytea_string from i+1 for 1);
     num3 := substring(bytea_string from i+2 for 1);
     output_number := 64*num1 + 8*num2 + num3;

     IF output_number = 0 THEN
        translated_string_array[npos] := E'\\000'::bytea;
     ELSIF output_number = 92 THEN
        translated_string_array[npos] := E'\\\\'::bytea;
     ELSE
        translated_string_array[npos] := chr(output_number)::bytea;
     END IF;
     npos := npos+1;
   END LOOP;

   RETURN array_to_string(translated_string_array, '');
END;
$$ LANGUAGE 'plpgsql';


--
Jochen Erwied     |   home: jochen@erwied.eu     +49-208-38800-18, FAX: -19
Sauerbruchstr. 17 |   work: joe@mbs-software.de  +49-2151-7294-24, FAX: -50
D-45470 Muelheim  | mobile: jochen.erwied@vodafone.de       +49-173-5404164


pgsql-performance by date:

Previous
From: Grzegorz Jaśkiewicz
Date:
Subject: Re: serveRAID M5014 SAS
Next
From: "Pierre C"
Date:
Subject: Re: FW: KVP table vs. hstore - hstore performance (Was: Postgres NoSQL emulation)