This post follows Seasonal Photos: Fun with Bash. Seasonal Photos is a function in which we're displaying the current season's photos from my Walking the Dog Collection with list items in an Android app I'm building. As I said in Fun with Bash, Seasonal Photos is an inconsequential little function, but one that has interesting pieces, like the Java performance patterns we're looking at today.
As covered in the previous post, photos are arranged by folder: winter, spring, summer and fall. Here's the visual for folders spring and winter.
The current season is determined by month. CurrentSeasonId is probably the most critical piece in determining the performance of generating the photo collection and retrieving a random image from the collection to associate with the data objects sent to the Android app.
We'll grab the current season ID from a PostgreSQL lookup table. Each photo has a seasonId assigned to it which we generated in Fun with Bash. Here's the SQL Schema for our Season Images. Lookup table is on the left, seasons top right, images bottom right.
We use CurrentSeasonId a lot, so we cache it to prevent multiple trips to the database. Once it's cached we have instant access for other calculations we'll need it for.
We're assigning a random image from the current season to each data object, and to do so we need the number of photos in each collection. This is another performance consideration. We could do something fancy with lambda like so:
int _imageCount = 0; int _currentSeasonId = getCurrentSeasonId(); return (int) getNixMashupImages() .stream() .filter(i -> i.seasonId ==_currentSeasonId) .mapToInt(i -> i.seasonId) .count();
While the above may look pretty, using lambda on the image collection is WAY slower than simple assignment to Integer Constants. We can use Constants since the photo collection counts are fixed and it isn't currently being added to. We don't have to cache the Season Image Count either.
You see a season enumerator used in assigning the current season image count. We also use it for generating the folder name, spring, summer, fall or winter.
This isn't so much about performance than it is about clean code. The above code to determine the season name is nice and simple because the ImageSeason Enumerator was fudged to accommodate the 1-base logic for our months and seasons. The insertion of a DEFAULT to handle the “0” value we're not using anywhere kept our logic simpler and cleaner when working with the enumerator.
For completeness we'll show how we're assigning the random image to the data collection. The data collection is created, then the image properties are updated from the cached image collection and the elements we covered earlier. Then the data collection is cached and we're good to go.
Pretty Java patterns and fast, too. Next time we'll look at the REST and Android side of Seasons Photos.