
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
196
|
Chapter 3: Classes and Structures
--> Add 5 weak references
OC.TotalCacheSlots = 5
OC.AliveObjsInCache = 5
--> Obtain ID1
SCOTemp.IDCode = 100
--> Obtain ID1, ID3, ID5
--> Collect all weak references
OC.TotalCacheSlots = 5
OC.AliveObjsInCache = 3
SCO1.IDCode = 1000
SCO3.IDCode = 3000
SCO5.IDCode = 5000
--> Get ID2, which has been collected. ID2 Exists ==False
ID2 has now been re-created. ID2 Exists == True
OC.AliveObjsInCache = 4
SCO2.IDCode = 2000
--> Collect all weak references
OC.TotalCacheSlots = 5
OC.AliveObjsInCache = 4
--> Collect all weak references
OC.TotalCacheSlots = 5
OC.AliveObjsInCache = 0
Discussion
Caching involves storing frequently used objects, particularly those that are expen-
sive to create and re-create, in memory for fast access. This technique is in contrast
to recreating these objects through some time-consuming mechanism (e.g., from
data in a database or from a file on disk) every time they are needed. By storing fre-
quently used objects such as these—so that you do not have to create them nearly as
much—you can further improve the performance of the application.
When deciding which types of items can be cached, you should look for objects that
take a long time to create and/or initialize. For example, if an object’s creation
involves one or more calls to a database, ...