Re: Speeding up loops in pl/pgsql function

From: Jochen Erwied <jochen(at)pgsql-performance(dot)erwied(dot)eu>
To: "Reuven M(dot) Lerner" <reuven(at)lerner(dot)co(dot)il>
Cc: pgsql-performance(at)postgresql(dot)org
Subject: Re: Speeding up loops in pl/pgsql function
Date: 2011-05-26 08:46:55
Message-ID: 589023449.20110526104655@erwied.eu
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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(at)erwied(dot)eu +49-208-38800-18, FAX: -19
Sauerbruchstr. 17 | work: joe(at)mbs-software(dot)de +49-2151-7294-24, FAX: -50
D-45470 Muelheim | mobile: jochen(dot)erwied(at)vodafone(dot)de +49-173-5404164

In response to

Browse pgsql-performance by date

  From Date Subject
Next Message Pierre C 2011-05-26 09:24:24 Re: FW: KVP table vs. hstore - hstore performance (Was: Postgres NoSQL emulation)
Previous Message Grzegorz Jaśkiewicz 2011-05-26 08:31:05 Re: serveRAID M5014 SAS