Skip to main content

Blogging about 11g : Function Result Cache

From the 11g New Features Guide:
"New in 11.1 is the ability to mark a PL/SQL function to indicate that its result should be cached to allow lookup, rather than recalculation, on the next access when the same parameter values are called. This function result cache saves significant space and time. Oracle does this transparently using the input actuals as the lookup key. The cache is system-wide so that all distinct sessions invoking the function benefits. If the result for a given set of actuals changes, you can use constructs to invalidate the cache entry so that it will be properly recalculated on the next access. This feature is especially useful when the function returns a value that is calculated from data selected from schema-level tables. For such uses, the invalidation constructs are simple and declarative.
Concurrent, multi-user applications that use this feature experience better response times. Applications that implement a session-private scheme consume significantly less memory by using this feature and, therefore, experience improved scalability."


Let's see if this statement is true:
First create a (simple) function with the 'result_cache' construct but without the 'relies_on' construct:

SQL> CREATE OR REPLACE FUNCTION CALC_SALARY_WITH_COMM
2 (p_emp_id EMPLOYEES.EMPLOYEE_ID%TYPE)
3 RETURN NUMBER
4 result_cache
5 --relies_on (employees)
6 is
7   l_salary employees.salary%type;
8   l_comm number;
9   l_result number;
10 BEGIN
11   select salary
12   ,      1 + nvl(commission_pct,0)
13   into   l_salary
14   ,      l_comm
15   from   employees
16   where  employee_id = p_emp_id;
17   l_result := l_salary * l_comm;
18   return l_result;
19 exception
20   when no_data_found
21   then
22     RETURN 0;
23 END;
24 /

Call the function and cache the results of the calculation

SQL> select
2    ,      last_name
3    ,      salary
4    ,      commission_pct
5    ,      calc_salary_with_comm( employee_id ) total
6 from employees
7 where last_name = 'King'
8 /

LAST_NAME SALARY COMMISSION_PCT TOTAL
--------- -----  -------------- ----------
King      10000                 10000
King      24000                 24000

Change the values used in the calculation

SQL> update employees
2 set commission_pct = 0.99
3 where last_name = 'King'
4 /

Issue the select statement again and check that the results of the calculations are not changed! (this is due to the lack of the "RELIES_ON" clause)

LAST_NAME SALARY COMMISSION_PCT TOTAL
--------- -----  -------------- ----------
King      10000             .99 10000
King      24000             .99 24000

When you create another session and issue the select statement in this session you'll see that the results are still from the cache...(because they're still 'wrong').

Reset the values used in the calculation

SQL> update employees
2 set commission_pct = null
3 where last_name = 'King'
4 /

Now recreate the function with the "RELIES_ON" clause

SQL> CREATE OR REPLACE FUNCTION CALC_SALARY_WITH_COMM
2 (p_emp_id EMPLOYEES.EMPLOYEE_ID%TYPE)
3 RETURN NUMBER
4 result_cache
5 relies_on (employees)
6 is
7   l_salary employees.salary%type;
8   l_comm number;
9   l_result number;
10 BEGIN
11   select salary
12   ,      1 + nvl(commission_pct,0)
13   into   l_salary
14   ,      l_comm
15   from   employees
16   where  employee_id = p_emp_id;
17   l_result := l_salary * l_comm;
18   return l_result;
19 exception
20   when no_data_found
21   then
22     RETURN 0;
23 END;
24 /

Issue the select statement and that will cache the results of the calculation
Change the values used in the calculation

SQL> update employees
2 set commission_pct = 0.99
3 where last_name = 'King'
4 /

Issue the select statement and check that the results of the calculations are changed now

LAST_NAME SALARY COMMISSION_PCT TOTAL
--------- -----  -------------- ----------
King      10000             .99 19900
King      24000             .99 47760

Reset the values used in the calculation

SQL> update employees
2 set commission_pct = null
3 where last_name = 'King'
4 /

Now do a little performance test

Create a similar function that doesn't cache

SQL> CREATE OR REPLACE FUNCTION CALC_SALARY_WITH_COMM_NC
2 (p_emp_id EMPLOYEES.EMPLOYEE_ID%TYPE)
3 RETURN NUMBER
4 -- result_cache
5 -- relies_on (employees)
6 is
7   l_salary employees.salary%type;
8   l_comm number;
9   l_result number;
10 BEGIN
11   select salary
12   ,      1 + nvl(commission_pct,0)
13   into   l_salary
14   ,      l_comm
15   from   employees
16   where  employee_id = p_emp_id;
17   l_result := l_salary * l_comm;
18   return l_result;
19 exception
20   when no_data_found
21   then
22     RETURN 0;
23 END;
24 /

First call the function 100.000 times without caching

SQL> declare
2 result number;
3 begin
4 for i in 1..100000 loop
5 select calc_salary_with_comm_nc( employee_id ) total
6 into result
7 from employees
8 where employee_id = 100;
9 end loop;
10 end;
11 /

PL/SQL procedure successfully completed.

Elapsed: 00:00:16.80

Next call the function 100.000 times with caching

SQL> declare
2 result number;
3 begin
4 for i in 1..100000 loop
5 select calc_salary_with_comm( employee_id ) total
6 into result
7 from employees
8 where employee_id = 100;
9 end loop;
10 end;
11 /

PL/SQL procedure successfully completed.

Elapsed: 00:00:09.78

In this example the result is that the cached version is 40% faster....

The cached results are visible in V_$RESULT_CACHE_OBJECTS. If the RELIES_ON clause is used the cached result becomes "Invalid" when (whatever which) data of the table is changed. Why these "Invalid" cached results are still available is a mystery to me (why aren't they deleted?).

It seems that using this feature you can enhance the performance (when used wisely...).

As specified, this feature is (very) usefull when a function returns a kind of (complex) calculation using non-frequently changed table(s) - or no tables at all.
Untill now a developer usually caches these kinds of values (like parameter values) in a package variable (or array), but that's a per session solution. Using this feature the cached results are available in every session! The risk is ofcourse that the developer "forgets" using the RELIES_ON clause (it is optional!).

Comments

Filipe Silva said…
"The risk is of course that the developer "forgets" using the RELIES_ON clause."
No more risk: in 11gr2 RELIES_ON clause is not necessary!

Popular posts from this blog

How to create neatly formatted Excel documents using PL/SQL?

If there is a requirement to produce output from an application into Excel, you would probably create a CSV (Comma Separated File) with the data and start Excel to show the data - at least that's what I did...until now. The drawback of this solution is that you could only produce data and no nice layout. But Excel is also capable of opening HTML-files and using this you could create Excel files with data and magnificent layout! Let me give an example: 1. Create a procedure to show the data in formatted in an HTML table. CREATE OR REPLACE PROCEDURE display_emp_list IS v_emp_count NUMBER(5); v_empno NUMBER(8); v_ename VARCHAR2(50); v_job emp.job%TYPE; v_sal emp.sal%TYPE; v_bg_color VARCHAR2(10) := ''; CURSOR c_emp IS SELECT empno, initcap(ename), job, sal FROM emp ORDER BY ename; BEGIN SELECT COUNT(*) INTO v_emp_count FROM emp; owa_util.mime_header('application/ms-excel', FALSE); htp.p('Content...

Refresh selected row(s) in an Interactive Grid

In my previous post I blogged about pushing changed rows from the dabatase into an Interactive Grid . The use case I'll cover right here is probably more common - and therefore more useful! Until we had the IG, we showed the data in a report (Interactive or Classic). Changes to the data where made by popping up a form page, making changes, saving and refreshing the report upon closing the dialog. Or by clicking an icon / button / link in your report that makes some changes to the data (like changing a status) and ... refresh the report.  That all works fine, but the downsides are: The whole dataset is returned from the server to the client - again and again. And if your pagination size is large, that does lead to more and more network traffic, more interpretation by the browser and more waiting time for the end user. The "current record" might be out of focus after the refresh, especially by larger pagination sizes, as the first rows will be shown. Or (even wors...

APEX ReadOnly Pages - The easy way

If your Oracle APEX Application requires different types of access - full access or readonly - for different types of users, you can specify a Read Only Condition on Page level (or Region, Item, Button, etc.).  You can set an Authorization Scheme on Application level, so it'll be applied to all pages. So if you have an Authorization Scheme named 'User Can Access Page' defined by a PL/SQL function like this: return apex_authorization.user_can_access_page ( p_app_id  => :APP_ID , p_page_id => :APP_PAGE_ID , p_user    => :APP_USER );  then you can code all the logic in the database using the APEX Repository, your own tables or a combination to define whether a user has access to that page or not. But alas it is not possible to define something similar Application wide for a Read Only condition. You can specify an Authorization Scheme 'User has Read Only Access' using a similar signature as the one above and use that on each and e...