Quantcast
Channel: Skypanther® Studios
Viewing all articles
Browse latest Browse all 25

Don’t create variables you don’t need

$
0
0

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 < $.product.photos.length; i++) {
  var photo = $.product.photos[i];
  var imgView = Ti.UI.createImageView({
  image: photo
  });
  // $.product_photos is a Ti.UI.ScrollableView
  $.product_photos.addView(imgView);
}

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 < $.product.photos.length; i++) {
  $.product_photos.addView(Ti.UI.createImageView({
  image: $.product.photos[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.


Viewing all articles
Browse latest Browse all 25

Trending Articles