I wrote a function in Oracle to convert IP addresses to integers. It seemed slow. I wrote a second function to do the same thing only faster. Unfortunately it ended up slower and I do not know why.
Original function;
FUNCTION GET_IP_INTEGER
(
IP_IN IN VARCHAR2
) RETURN NUMBER AS
DOT_COUNTER INTEGER;
CURRENT_DOT INTEGER;
LAST_DOT INTEGER := 1;
CURRENT_INTEGER INTEGER := 0;
OUTPUT_INTEGER INTEGER := 0;
BEGIN
FOR DOT_COUNTER IN 1..3
LOOP
CURRENT_DOT := INSTR(IP_IN,'.',LAST_DOT);
CURRENT_INTEGER := TO_NUMBER(SUBSTR(IP_IN,LAST_DOT,CURRENT_DOT - LAST_DOT));
LAST_DOT := CURRENT_DOT + 1;
CASE DOT_COUNTER
WHEN 1 THEN CURRENT_INTEGER := CURRENT_INTEGER * 16777216;
WHEN 2 THEN CURRENT_INTEGER := CURRENT_INTEGER * 65536;
WHEN 3 THEN CURRENT_INTEGER := CURRENT_INTEGER * 256;
END CASE;
OUTPUT_INTEGER := OUTPUT_INTEGER + CURRENT_INTEGER;
CURRENT_INTEGER := 0;
END LOOP;
CURRENT_INTEGER := TO_NUMBER(SUBSTR(IP_IN,LAST_DOT));
OUTPUT_INTEGER := OUTPUT_INTEGER + CURRENT_INTEGER;
RETURN OUTPUT_INTEGER;
END GET_IP_INTEGER;
It picks everything apart and works well. But I thought I could do better so I wrote this;
FUNCTION GET_IP_INTEGER1
(
IP_IN IN VARCHAR2
) RETURN NUMBER AS
OCTET_COUNTER INTEGER;
CURRENT_INTEGER INTEGER := 0;
OUTPUT_INTEGER INTEGER := 0;
BEGIN
FOR OCTET_COUNTER IN 1..4
LOOP
CURRENT_INTEGER := TO_NUMBER(REGEXP_SUBSTR(IP_IN,'\w+',1,OCTET_COUNTER));
CURRENT_INTEGER := POWER(2,24 - ((OCTET_COUNTER-1)*8)) * CURRENT_INTEGER;
OUTPUT_INTEGER := OUTPUT_INTEGER + CURRENT_INTEGER;
END LOOP;
RETURN OUTPUT_INTEGER;
END GET_IP_INTEGER1;
This also works but seems to run much (about twice as long) slower. I would assume that either the power function or the regexp_substr is a pig. But I was hoping someone with more knowledge might point out which, and/or why.