Fast REVERSE() function? - Mailing list pgsql-hackers

From Chris Browne
Subject Fast REVERSE() function?
Date
Msg-id 877i9m4qbx.fsf_-_@dba2.int.libertyrms.com
Whole thread Raw
Responses Re: Fast REVERSE() function?  ("Mario Weilguni" <mario.weilguni@icomedias.com>)
Re: Fast REVERSE() function?  (hubert depesz lubaczewski <depesz@depesz.com>)
List pgsql-hackers
I've got a case where I need to reverse strings, and find that, oddly
enough, there isn't a C-based reverse() function.

A search turns up pl/pgsql and SQL implementations:

create or replace function reverse_string(text) returns text as $$
DECLARE
reversed_string text;
incoming alias for $1;
BEGIN
reversed_string = '''';
for i in reverse char_length(incoming)..1 loop reversed_string = reversed_string || substring(incoming from i for 1);
end loop;
return reversed_string;
END $$
language plpgsql;

CREATE OR REPLACE FUNCTION reverse(TEXT) RETURNS TEXT AS $$SELECT    array_to_string(      ARRAY       ( SELECT
substring($1,s.i,1) FROM generate_series(length($1), 1, -1) AS s(i) ),      '');
 
$$ LANGUAGE SQL IMMUTABLE;

Unfortunately, neither is particularly fast.  This should be
"blinding-quick" in C, in comparison; reversing a set of bytes should
be able to be done mighty quick!

(Aside: presumably we could walk thru the string destructively,
in-place, swapping bytes; I think that would be theoretically
quickest...)

I could probably add this in as an SPI() function; is there a good
reason to try to avoid doing so?
-- 
output = reverse("ofni.sesabatadxunil" "@" "enworbbc")
http://www3.sympatico.ca/cbbrowne/sgml.html
"Consistency  is  the  single  most important  aspect  of  *ideology.*
Reality is not nearly so consistent." - <cbbrowne@hex.net>


pgsql-hackers by date:

Previous
From: Gregory Stark
Date:
Subject: Re: [PATCH] Cleanup of GUC units code
Next
From: Tom Lane
Date:
Subject: Re: For what should pg_stop_backup wait?