Looping Backwards to Avoid IOB Errors and Record Skipping
"Caching" your Query Result for Better Performance
Consider the following DSL snippet:
Children[] cs1 = /*backing selector*/
for (int i = 0; i < cs1.length(); i++) {
/*loop code*/
}
If the size of the collection cs1 were to change due the loop code removing an item from the list (e.g. by updating an attribute which will exclude it from the selector's result), the selector (and the ensuing SQL query) will execute again to update the collection. If it's a complex selector resulting in a resource intensive SQL query, it might slow down performance significantly.
One way to handle this is to create a new, "static" list, copied from the dynamic list. For example, cs2 in the code below will not be refreshed, and iterating over it will not cause the cs1 backing selector te be re-executed for each iteration causing a collection size change:
Children[] cs1 = /*backing selector*/
Children[] cs2;
for (int i=0; i < cs1.length(); i++){
cs2.append(cs1.get);
}
for (int c = 0; i < cs2.length(); c++){
/*loop code*/
}
You can think of cs2 in the above snippet as a cached copy of cs1. Using static in addition to dynamic lists is, however, not considered to be best practice in all scenarios, and should be evaluated on a case by case basis. It's a good idea to "cache" your collection when most or all of the following apply:
The likelihood of items being changed when looping over them, and thus the likelihood that the collection will need to be "refreshed" resulting in the selector being executed again, is high
The backing selector is complex and will execute a resource intensive query
The typical amount of data being processed or iterated over is high
It's relatively quick to copy the collection contents to a different collection
No labels
0 Comments
You are not logged in. Any changes you make will be marked as anonymous. You may want to Log In if you already have an account.
0 Comments