Java Reference
In-Depth Information
As the code loops through the stock and visits each collection of option prices, JPA will issue
SQL statements to retrieve all the options associated with the particular entity (that is, it re-
trieves the entire collection for one stock/date combination at once). This occurs at SQL Call
Site 2, and it results in 33,408 individual SELECT statements during execution (261 days *
128 stocks).
That example takes almost 62 seconds for the first execution of the loop. The next time that
code is executed, it takes only 3.2 seconds. That's because the second time the loop is ex-
ecuted, the only SQL that is executed is the named query. The entities retrieved via the rela-
tionship are still in the L2 cache, so no database calls are needed in that case. (Recall that the
L2 cache only works for entities loaded from a relationship or a find operation. So the stock
option entities can be found in the L2 cache, but the stock prices—since they were loaded
from a query—do not appear in the L2 cache and must be reloaded.)
The second line in Table 11-3 represents the code that does not visit each of the options in
the relationship (i.e., the processOptions variable is false ). In that case, the code is sub-
stantially faster: it takes 5.6 seconds for the first iteration of the loop, and 2.8 seconds for
subsequent iterations. (The difference in performance between those two cases is due to the
warm-up period of the compiler. Although it wasn't as noticeable, that warm-up occurred in
the first example as well.)
Caching and eager loading
In the next two experiments, the relationship between the stock prices and option prices is re-
defined so that the option prices are loaded eagerly.
When all the data is used (i.e., the first lines in Tables 11-3 and 11-4 , the performance of the
eager and lazy loading cases is essentially the same. But when the relationship data isn't ac-
tually used (the second lines in each table), the lazy relationship case saves some
time—particularly on the first execution of the loop. Subsequent executions of the loop don't
save time since the eager-loading code isn't reloading the data in those subsequent iterations;
it is loading data from the L2 cache.
Table 11-4. Seconds required to read data for 128 stocks (eager loading)
Test case
First execution
Subsequent executions
Eager relationship
60.2 seconds (33,409 SQL calls) 3.1 seconds (1 SQL call)
Eager relationship, no traversal 60.2 seconds (33,409 SQL calls) 2.8 seconds (1 SQL call)
Search WWH ::

Custom Search