Performance of regexp_replace vs translate in Oracle?

后端 未结 2 1474
一整个雨季
一整个雨季 2020-12-19 03:20

For simple things is it better to use the translate function on the premise that it is less CPU intensive or is regexp_replace the way to go?

2条回答
  •  心在旅途
    2020-12-19 03:41

    For SQL, I tested this with the following script:

    set timing on
    
    select sum(length(x)) from (
      select translate('()', '()[]', '----') x
      from (
        select *
        from dual
        connect by level <= 2000000
      )
    );
    
    select sum(length(x)) from (
      select regexp_replace('[()]', '[\(\)\[]|\]', '-', 1, 0) x
      from (
        select *
        from dual
        connect by level <= 2000000
      )
    );
    

    and found that the performance of translate and regexp_replace were almost always the same, but it could be that the cost of the other operations is overwhelming the cost of the functions I'm trying to test.

    Next, I tried a PL/SQL version:

    set timing on
    
    declare
      x varchar2(100);
    begin
      for i in 1..2500000 loop
        x := translate('()', '()[]', '----');
      end loop;
    end;
    /
    
    declare
      x varchar2(100);
    begin
      for i in 1..2500000 loop
        x := regexp_replace('[()]', '[\(\)\[]|\]', '-', 1, 0);
      end loop;
    end;
    /
    

    Here the translate version takes just under 10 seconds, while the regexp_replace version around 0.2 seconds -- around 2 orders of magnitude faster(!)

    Based on this result, I will be using regular expressions much more often in my performance critical code -- both SQL and PL/SQL.

提交回复
热议问题