Starter Step

Archive for the ‘C#’ Category

Brian and I have been working on improving the startup of TripCase and have found some interesting items. Our startup on TripCase slow…eventually we think we will move to a more facebook style model where much of your data is stored locally on the device. This will allow us to show the main view of TripCase without the 6-N seconds of time to talk to the server first. While the page loads with the cached data we can asyncronously retrieve the live data and update the view….but I digress.

We were debugging our message stream on the main view and noticed that the first cell was taking almost a full second to create. All subsequent cells were taking on the order of .15 – .20 seconds. After some NSLogs here and there we finally tracked down the culprit! In our app we implemented a “time ago” feature that tells you relatively how long ago something occurred. It is a nice feature and lets users see that something was created a few minutes ago, a few hours ago, etc. Its pretty granular and makes for a good experience. The times we convert to timeago are given to the client through our server and are all in GMT. This means that in timeago we need to create a NSDateFormatter with a mask that includes timezone. Our poor performing code looked something like the following:

+(NSString *)timeAgo:(NSString *)_date {
	static NSDateFormatter *parser = nil;
	if (parser == nil) {
		parser = [[NSDateFormatter alloc] init];
                [parser setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];      
		[parser setFormatterBehavior:NSDateFormatterBehavior10_4];
		[parser setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss z"];
	}
	NSDate *date = [parser dateFromString:[_date stringByAppendingString:@" GMT"]];
	double littleOverAWeek = 11520.0f;
	NSDate *now = [NSDate date];
	double deltaMinutes = fabs([date timeIntervalSinceDate:now]) / 60.0f;
	if(deltaMinutes < littleOverAWeek){
		return [NSString stringWithFormat:@"%@ ago", [self distanceOfTimeInWords:deltaMinutes]];
	} else {
		return [NSString stringWithFormat:@"on %@", [DateFormatter shortDateFromDate:date]];
	}
}

In the above method, we create a NSDateFormatter with a mask of “yyyy-MM-dd’T’HH:mm:ss z”. Seems pretty harmless right? Wrong! Brian and I removed the “z” and timed the creation of the NSDateFormatter. We saw that with the “z” in the mask, the creation of the NSDateFormatter was .7 seconds slower!! 700 milleseconds is a lifetime. We saw that during startup we create two NSDateFormatters that were doing this…that is 1.5 seconds of wasted time that we wanted to remove.

In the docs we noticed that you can set the timezone for the NSDateFormatter explicitly. We did that and the .7 seconds of invocation time went away…BAM! We just shaved 1.5 seconds from our startup time. Our new code looks something like this:

+(NSString *)timeAgo:(NSString *)_date {
	static NSDateFormatter *parser = nil;
	if (parser == nil) {
		parser = [[NSDateFormatter alloc] init];
                [parser setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];       
		[parser setFormatterBehavior:NSDateFormatterBehavior10_4];
		[parser setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
		[parser setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
	}
	NSDate *date = [parser dateFromString:_date];
	double littleOverAWeek = 11520.0f;
	NSDate *now = [NSDate date];
	double deltaMinutes = fabs([date timeIntervalSinceDate:now]) / 60.0f;
	if(deltaMinutes < littleOverAWeek){
		return [NSString stringWithFormat:@"%@ ago", [self distanceOfTimeInWords:deltaMinutes]];
	} else {
		return [NSString stringWithFormat:@"on %@", [DateFormatter shortDateFromDate:date]];
	}
}

Two things to notice in the above code:
1. We set the timezone context directly on the NSDateFormatter which allowed us to remove the “z” from the mask.
2. Doing this also allowed us to remove the ugly code that was appending GMT to the time returned from the server.

All of our timings were done on a 3G device. In all we shaved roughly 1.5 seconds because this pattern was used in two places during startup. Score 1 for super sleuthing!

If you have ever chatted with me about programming languages, its terribly obvious that I love ruby. Its just plain fun to write ruby code. I wouldn’t call myself a ruby nazi, but I would say that I get excited when I can do ruby like things in other languages. I have been working with C# for about two months getting TripCase on the Windows Mobile platform. My appreciation for c# is actually growing more and more. We use lambdas quite frequently in our Windows Mobile implementation which makes our code look alot like ruby.

Just yesterday I wanted to titleize a piece of text. My goal would be to just call:

   "jake loves ruby".Titleize();

Unfortunately the method wasn’t available….until I wrote this:

public static class StringExtensions
    { 
        public static string Titleize(this string text)
        {
          CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text)
        }
    }

Now I can call my Titleize method as if it were a method on an instance of the String class. Cool huh….yeah I thought so. You can read more about extension methods (thats what the c# kids are calling it) here

Update:
While this is cool, I could not figure out how to take an already existing method on a class and extend its behavior. In ruby we can do this with our method alias trick….but still..props to c# for extensions.

So yeah…its known that I’m a Mac guy and have sworn off Windows. However, my recent project has me building TripCase on the Windows Mobile platform. We have already built for the iPhone. Brian is hard at work on the BlackBerry version. Needless to say…we are swamped. Anyhow, I digress.

So working with C# has been actually interesting. I am finding that I “like” the language. It reminds me of Java, done better. It has features that are kinda ruby like. I have also been using Linq. Its a query language for parsing all types of enumerables. For TripCase we built RESTful webservices that all of our clients interact with. With that said, we deal alot with XML on this project. Linq has actually been a big help. I’ll try to post some examples of its use later. I’m sure you uber Linq users will laugh at my elementary understanding…but hey…for us guys getting started…examples rock!!



  • Dave: I can tell you're a ruby guy because you forgot the 'return' keyword. Thanks for the tip though!
  • Chandrashekhar H M: Hi, Thanks its working fine in iOS 6 but not in iOS 7.0. Any Suggestion on this.
  • Coeur: To change a rootViewController, without all this TVNavigationController : myNewRoot = [[UIViewController alloc] init]; myNavigationController.view