Performance of foreach vs classic for in C#

I found a list of the eight most common mistakes developers make in C#.

I share the opinion of the author regarding string concatenation and retrieving or saving data to BD in more than 1 call. A a lot of bad string concatenations eats your memory and N+1 anti-pattern when accessing BD breaks your app performance.

The post was useful for me as I learnt how rethrowing exception actually works. Very interesting. But I don’t buy the rest of the list, I think they can only be applied in very specific scenarios and they are not golden rules.

The entry number 7 of the list, the foreach vs for, called my attention. I had always suspected that for is faster than foreach but I had assumed that it was for a very little margin. I wanted to test if for myself, so I prepared a little solution and by the way I tested the performance of iterate an array vs generic list.

The result is this:
Graph

From left to right, the first column is the result from a for through a List, in which the constraint is the count property of the list cached on a variable:

var collection = new List();
[...]
var count = collection.Count;
for (int i = 0; i < count; i++)
{
  int aux = collection[i];
}

The second column is the same for loop, but this time the loop constraint is the property Count directly. The property will be evaluated in each iteration.

var collection = new List();
[...]
for (int i = 0; i < collection.Count; i++)
{
  int aux = collection[i];
}

The third column is a foreach through the List

var collection = new List();
[...]
foreach (var i in collection)
{
  int aux = i;
}

Next columns are the same loops as above but iterating through a primitive array. The times are expressed in milliseconds and my machine is an Intel i3 with 6GB RAM running Windows 8 x64. I am using Visual Studio 2012. The collection and the array have 10 million items to run the tests.

As I already said, I expected a little advantage for the for loop against the foeach, and there it is, a roughly 20%. But what I did not expected was that iterating through a generic list takes the double of the time than iterating trough an array, so bad.

There was another surprise, the gap from caching the limit of the for or not. I suppose that the count property from List is some kind of cache but evaluating the property in the loop hurts performance in about 40%. I can’t imagine why it occurs. That should be a getter of a private primitive integer field.

Pkpass Android Viewer Source Code

I spent some time during 2012 Christmas in training my Android skills. I wrote a simple pkpass file viewer. It only supports event ticket types, but there should be enough code to support easily the other types.

Note that this is only a viewer, there is no support for push notifications or other functionality from pkpass.

The features are:
* It draws the event ticket on the screen
* It checks the integrity of the files using the SHA1 hash of the manifest file.
* It does not check the cryptographic signature

The repo on github is:

https://github.com/fmanso/android-pkpass-viewer

How to set a background image in a layout depending on the SDK version in Android

If you aim to develop a triple A app you need to care about the fragmentation. And fragmentation can be really annoying in Android.

There is tons of mobile phones and tablets that work with Android, each of them have a different pixel density, aspect ratio, resolution, display dimensions, etc. Even worse, Google has evolved Android a lot from first version and that means a lot of API changes in the SDK. If you want your app to work fine in all mobile phones and tablets you need to care about it.

The solution found by Google to face the API fragmentation if I understood it well is to compile with latest versions of SDK as target, but in the code do not use native API calls of the latest SDKs, instead use optional libraries, called legacy support libraries, that mirrors SDK native functionality. In that way older SDK versions get the new functionality of the new Android versions. Eclipse ADT plugin has options to download the support libraries automatically.

An API change I encountered in a personal project is the setBackgroundDrawable method from View class being deprecated starting at API level 16, the new one is called setBackground with the same arguments.

Dealing with this kind changes is easy. To avoid runtime errors, you only need to check what version of SDK is running and call the correct method.

The code should be something like this:

if (Build.VERSION.SDK_INT < 16) {
  this.layout.setBackgroundDrawable(new BitmapDrawable(this.getResources(), bitmap));			
} else {
  this.layout.setBackground(new BitmapDrawable(this.getResources(), bitmap));			
}

How to draw 1D/2D barcodes in Android

In a personal project I need to draw barcodes in an Android app. It is not difficult to do but for sure I will save some minutes of googling for you.

After reviewing some free libraries to draw barcodes I picked zxing.

http://code.google.com/p/zxing/

There are other libraries but zxing is the only one I found that let me draw QR, Aztec and PDF417 formats. And I need them for my project.

After downloading the zip, you will find that there a lot of source code for different targets. You only need to add core.jar from core folder to your project. There are specific folders for Android, but I think that they are for scanning barcodes, and we are here only for drawing them.

Ok, after adding core.jar to our class path, the sample code to draw a barcode is:

com.google.zxing.Writer writer = new MultiFormatWriter();
String stringToEncode = "https://n00bcoder.wordpress.com";
int pixelsWidth = 300;
int pixelsHeight = 300;
com.google.zxing.BarcodeFormat zxingFormat = BarcodeFormat.QR_CODE;
BitMatrix result = writer.encode(stringToEncode, zxingFormat, pixelsWidth , pixelsHeight);

int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
  int offset = y * width;
  for (int x = 0; x < width; x++) {
    pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
  }
}		
Bitmap barcode = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
barcode.setPixels(pixels, 0, width, 0, 0, width, height);

Then, the barcode bitmap can be added to a ImageView.

this.barcodeImageView.setImageBitmap(barcode)