Don’t create variables you don’t need

By | July 10, 2015

We were having a problem in our app where occasionally photos would load only partway. You’d see the top portion of the photo and the rest would be white.

In testing, I was not seeing network errors. Nor was memory being exhausted. Listening in on the ImageView’s error event showed no errors being reported. It wasn’t always the same image that would fail and when one failed to load, later images on the page would fully load. Finally, the images would usually load if you refreshed the screen.

With these clues in hand, I was fairly confident that the image files weren’t bad, memory wasn’t the issue, and the network probably wasn’t the source of the problem either.

Here’s the Titanium the code I inherited:

for (var i = 0; i < $; i++) {
  var photo = $[i];
  var imgView = Ti.UI.createImageView({
  image: photo
  // $.product_photos is a Ti.UI.ScrollableView

My supposition is that the loop was running faster than the ImageView creation. Before the image could be fully rendered the loop would overwrite the photo and imgView variables.

Based on that hunch, I refactored the code to:

for (var i = 0; i < $; i++) {
  image: $[i]

(Yes, I could/should have used a more functional approach… Move along.)

Since making this change, we haven’t seen the partial-image problem. It could be coincidence, or eliminating unnecessary variables might have resolved our issue. Only more testing will tell for sure.

Regardless, there’s no need to create variables as our code originally did. It can cause garbage collection issues and contribute to over-consumption of memory. And could lead to oddball problems like the ones we were seeing.