The Android Toolbox project

The other day I was working on one of my side projects written in Ruby on Rails, and I was in need of a gem  (third party libraries are called gems in Ruby) for performing syntax highlighting. After a few seconds of research, I stumbled upon this page from The Ruby Toolbox which lists all the available gems for handling this particular task. That is clever! Now, whenever I need to do a task that I think could be better achieved using a gem,  I just go to The Ruby Toolbox looking for the right category and I can see how good the community think the gem is and how many times it has been downloaded. Ultimately, in 5 mins I am able to pickup the right gem for the particular task that I am trying to achieve.

I want to build the same thing for Android!  The reason for this is that I can’t think of any place where I can find a list of third party libraries targeting Android development. Of course, we have things like Android UI Patterns that list a fair amount of libraries but as its name suggests, it is only related to UI Patterns and nobody can contribute by suggesting new libraries, nor is it possible to rate those libraries.

As far as the requirements are concerned, the user should be able to:

  • Browse and download libraries by category (Barcodes scanning, In-App payement, Advertisement, Geolocation, UI Patterns, Social, Data Oriented libraries, Testing libraries etc.).

  • Rate and post feedbacks on any library.

  • Propose a new library.

But before I start working on this, I would like to get your feedbacks on this idea. There is also a fair amount of chance that this project does already exist in a way or another (even if I have done some research and haven’t found anything close to what I have just described).

Finally, I would like to know if there are people interested in joining me on this project. Two guys can do a better work than one guy, if only because they can bounce ideas off of each other. So if  you are interested, I definitely want to talk to you!

That’s it! Looking forward to reading  your comments on this!

Introducing Digikod. My first personal android published app!

(by Claudecf)

The last few days, I have been busy coding an Android application called: Digikod. I am happy to announce, that the first version of this application is now published on the Market. So what does this application do? Let me answer through a serie of Q/A.

What is Digikod

Digikod is an application that helps you keep and organize all your Door-Lock Pin Codes in one place.

Why did you develop it?

These last weeks have been pretty intense in term of social interactions (= me going to other people’s houses a LOT) and I have to admit, although I am still very young, I have had some serious issues trying to memorize their building’s Door-Lock Pin Codes. And sometimes, when I was in front of the door I have had those moments where I asked myself: « Was it 4890B or 4890A or wait… may be it was 4590A… ». So this is my answer to this issue! We all have many codes to memorize (home, workplace, girlfriend, parents, gym etc.) and I hope this application will help you with that.

What are all the features of Digikod?

This is version 1.0, you can call it MVP (Minimum Viable Product) if you want, so it has the least amount of features:

  • You can add a Door-Lock Pin Code through a friendly user interface:

  • You can associate a location to your code:

- Finally, you can access the list of all your codes sorted by proximity:

That way, when you arrive at the given location you will be able to look quickly at the information that matters to you the most: the Door-Lock Pin Code of the door in front of you :-) (Killer feature right?).

Are you going to add other features to this application?

Sure I’ll do, I have some ideas about some features I could add to this application. For instance:

  • Protect the codes by  password. Although, I assume you are already protecting your phone against thiefs (with a lock pattern screen for instance), adding this feature could make sense.

  • Add a Widget which only shows the code of the nearest building.

  • Improve the friendliness of the app, by adding states to each button for instance (normal, focussed, pressed) .

  • Improve the navigability by adding an Up button to the ActionBar.

  • Interfacing this application with your contacts list.

How much time did you spend developing this?

I started it last week as a side project. I guess I have been able to code only 2 hours a night (even on the Week-Ends), so that’s about 15 hours at most.

What does Digikod mean?

The word Digikod comes from the french word Digicode which is a registered trademark for Door-Lock Pins. This trademark is owned by CDVI France, but apparently the guy who invented it is a french engineer whose name is: Bob Carrière.

Why is it only possible to enter one of the following characters: 0…9, A, B, #, * ?

Because I think those are enough (at least in France, I don’t know about other countries! Please let me know if you have special pads with other characters, I’ll add the possibility to type custom codes right away).

Did you do this alone?

As far as programming is concerned, yes. However, I’d like to thank Ghislaine Guerin for helping me with the design work. She provided a bunch of valuable resources and she made a lot of great suggestions on how the different screens should look like.

Where I can get it?

On the Android Market of course (it’s free!!), you can also grab it from this QR Code:

Conclusion

I have to say that I’m glad that I have been able to publish this app within a week. I developed it for myself because I really needed to keep all my Pin Codes in one place and now, I am sharing it for free in case someone else needs it.

Finally, if you download this application,  I’d appreciate any comment/suggestion in order to make it better.

My first impressions on Ice Cream Sandwich (Nexus S port)

Earlier this morning I saw this tweet from the Google Nexus Twitter account:

Great news, since I own a Google Nexus S device. And instead of waiting for the update to be rolled out on my device over the air, I decided to install it myself. The update went fine, and after playing a bit with ICS I can now give you my first impressions on ICS.

First, I will start talking about what I didn’t like in ICS and then I’ll tell you about things that I liked.

What I didn’t like in ICS

  • The general experience feels laggy and slow  (at least slower than what I was used to with Gingerbread). Everything takes a lot of time to load like on the native phone app. In order to confront my intuition against some real proof, I ran some benchmarks on Quandrant and Antutu and the results were disappointing.

The screenshots are explicit.  The only satisfaction is probably on the 3D graphics performances and yes I have felt that as well while playing some 3d games (like Shine Runner).

  • Some of the games that used to work just fine before, are crashing now. Heavy Gunner 3D is an example of that. Oh and I also noticed that the force close dialog is no longer displayed when an app crashes.
  • The contacts page is ambiguous. I couldn’t find how to modify the information of any contact. Usually, a single press on any row would bring me to a detailed page where I could change the info of the contact. Now, a single press will just make the phone call.
  • Fun bug. Restart your phone in order to bring up the PIN code page. Start typing your code, but before pressing ok,  turn your screen off. Now turn your screen on again and, tadaaa the code is now gone. These sort of bugs just don’t make the overall product look professional.

What I liked in ICS

  • The clear separation between widgets and apps on the menu page. I have to say, that on former versions of Android, I had a tendency to forget about widgets because they were hidden. Now that they are visible, I can see what applications have widgets and this will make me more of a widget guy.
  • The new notifications are gorgeous. First the drawer is now transparent, which gives us the possibility to keep a look on what is running behind.

  • To continue on the notifications, we can now delete them manually which was really missing before.
  • To finish on the notifications, I like that we can now read more about the content of the notifications. For instance, when you receive a new mail you will actually know who sent you that email and its title, right from the notifications tray.
  • Holding the home button, brings you a list of all the running apps. In order to kill one app, you only need to swipe it from left to right. Very useful. I can now delete Advanced Task Killer.

  • At last, it’s now possible to take screenshots right from the phone. All you need to do, is to hold the volum down button and the power button. Apparently that featured existed on some Galaxy phones but not on other devices.
  • Voice recognition works great. I just typed an entire email with it and it makes n0 mistakes. Also, it’s worth mentionning that the result of the recognition is dynamically shown on screen. This is huge.
  • Another sweet feature, is the possibility to group icons in folders on the home page. All you have to do, is to drag an icon and drop it into another icon to form a group. This feature is awesome. I can now organize my space more wisely.
  • Dragging apps from one screen to another on the home page, is easier.
  • This is subjective, but I find that the new animations are better. For instance the transition animations (when moving from one activity to another) are more… polished, less brutal. I also like the animation on the menu page, when swiping through the pages.
  • I also noticed, that the software buttons (back , search , menu and home)  are not shown on the Nexus S, because it already has the physical ones. Smart.
  • The new font (called Roboto font) is very beautiful. It’s sharp and very pleasant to look at.

To summarize

Ice Cream Sandwich has very nice new features that makes the life of Android users easier. However, I regret that it slowed down my Nexus S as shown on the different benchmarks that I ran. I also regret some bugs on apps that use to work well before (games, the photo app that crashed before the phone was plugged to my computer in storage mode etc.). I hope Google will do its best to fix all these issues as soon as possible. Finally, I have to say that I approve this update and I feel that once I will be used to all these changes, it will be hard for me to get back to older Android versions.

Stop making beautiful apps and start making useful apps

Recently a lot of hot mobile apps (both on iOS and Android) have been published by major Startups from the Silicon-Valley, like Flipboard,  Path or Any.Do. What do these apps have in common? They all address a very saturated market,  and their only way to shine is to differentiate themselves from other apps through excellence. An app that is excellent, is an app  that is both beautiful and easy to use. It’s an app that makes you happy whenever you use it. It’s an app that has some magic inside its hat. Generally they all have that single feature that everyone is going to remember and talk about. Path has that beautiful and smooth animated radial menu and Flipboard is a piece of art, you can flip through the articles like a magazine, but vertically instead of horizontally in order to compensate the size of the screen on the iPhone that is smaller than the one on the iPad.

I have a confession though, I have been using Path for only 2 days. Why? Because I just don’t need it. Yes, I can survive without it since none of my friends are actually there and I, sincerely, don’t need another fuck**g social app. In fact Facebook/Twitter and may be Google+ cover all my social needs. But although I’m not using it, I have it still installed on my Nexus S because I often need to refer to it when talking about high quality apps (especially with clients).

On the other hand, I can see myself as a regular user of  Flipboard because the app is useful (can’t say that I am a regular user, since I don’t own any iOS device yet).

The conclusion of this, is that building an excellent app in a saturated market, is only a necessary condition. Nothing more. So please, before building any app, question yourself about whether your app could be useful in any capacity. Yesterday, I have read an article written by yongfook titled: Design is Horseshit. I strongly recommend you to read it, basically he is saying that Startups should be focusing more on creating value than on creating something that is just beautiful. I couldn’t agree more with him, I think design became overhyped (especially since Steve Jobs’s death). Don’t get me wrong, I am not saying that having a good design isn’t important but if the product isn’t useful in the first place, then people will just toss it away. And if you show me two apps, one that is beautiful and useless and the other one that is ugly but useful,  then I’ll go for the latter one on a regular basis (unless I find a suitable replacement for it by the way). This is best explained by this short clip from How I met your mother:

Basically Barney Stinson (What’s his job? Please!) stipulates that a girl is allowed to be Crazy, as long as she is equally Hot. I feel the same for apps. An app is allowed to be Ugly as long as it is equally Useful.

Actually, I think I’ll make my own theory here,  by sorting apps on their hotness/ugliness and their usefulness/uselesness scale. To clarify, let’s consider this chart:

As you can see, I have listed a few apps that you probably all know. Among these apps, I am only using those that are situated on the right side of the chart. Path is freaking hot, but not that useful. Badoo is not only useless but I have found their Android app to be a horrible, horrible piece of shit! Consider Prixing, which is an app that allows you to compare prices and helps you find whether some food has any suspicious ingredient (that will hurt your body if you follow a special diet for instance). Well, Prixing is a good example of an app that is not hot (well to be honest, it’s not hot but the design is simple and intuitive which is all that counts at the end) but very useful.  No matter how hot Path will become, I don’t see myself using it in the future.  On the other hand, no matter how ugly and laggy Prixing will become, I will always keep it on my device. Why? Because I can’t live without it. Of course, if you succeed into building an app that is both beautiful and useful then you are doing great, keep it going.

But please, stop making only good looking apps and start making useful apps. My device needs them more.

Why I like Uber

In case you missed it, Uber is an application that lets you request a car from your smartphone (there is an iOS version and an Android version). Up until recently, Uber only worked in a bunch of US cities (San Francisco, New York City, Seattle,  Chicago, Boston and Washington DC) but now it also works in Paris. I was thrilled at this news, first because I can see myself using it someday in one of these two situations:

  • It’s 4 AM and I feel too bad to look for a regular cab or to take the Noctilien (A night bus service in Paris).

  • I lost my wallet that contained my credit card, my navigation pass and all my cash and I am too far from home to get there by walk. Since Uber requires you to associate a credit card during the subscription , you don’t have to pay anything to the driver because your will be automatically charged for the ride (even     the tip is included).

By the way there might other occasions but right now I can only see these two, given that the service is a little bit expensive.

But the reason why I have a thing for Uber is that I (with two other persons) tried to build a similar service once.

Back in 2008 I decided (with two friends: Souad and Safa) to enter an annual competition sponsored and hosted by Microsoft, called Imagine Cup. Each year there is a theme and in 2008 we had to come up with solutions for protecting the environment. So back in August 2007, we started brainstorming many ideas,  sketching them and after literally 3 months we had that *Eureka* moment when we thought about building a real-time carpooling solution.

Introducing PickMeUp

PickMeUp was a mobile application that let you request a ride in real-time. It worked exactly like Uber except for one thing: every user could become a driver, whereas in Uber you have to be an official driver. This is the main reason why we used the word carpooling when pitching our idea while Uber doesn’t. Apart from this difference, there were many similarities in the way the product has been designed:

  • The positions of both the drivers and the riders were shown dynamically on a map.

  • Each user had an associated profile to match drivers and riders by their mutual interests.

  • After a ride, each of the driver and rider were invited to complete a feedback form and rate their partner according to the experience they had.

  • The price of the ride was calculated using a combination of both the distance between the pick up point and the  destination, and the duration of the ride.

  • The users who didn’t have a Windows Mobile Phone, could have used the service by sending SMSs.

Yes you have read that last sentence right, the app was really built on a Windows Mobile device. In case you don’t believe me, here is a short demonstration that we used as a proof of conceptfor that competition (full disclosure: this is the first real app I have ever built, don’t expect much from the UX nor the quality of the demonstration) :

A few things you may have noticed:

  • The map was provided by Microsoft MapPoint (it’s funny right?).

  • It took us 4 months to build this prototype. Most of this time was spent working on the backend, on real-time issues and various optimisations. Very little time was spent on the design and the user experience of the application. Actually this application was built before mobile became trendy, it was only a few months after the iPhone came to the Market and way before the release of Android. As a matter of fact, the bar wasn’t very high and all the apps looked as crappy as this one on these kinds of platforms. Needless to say that I’m really embarrassed by this demo but heck, that was my first app ever and you can only learn by trying and making things. I knew that I sucked and I know that I still suck (probably less than before) but this is the reason why I wake up everyday: to suck less.

  • We somehow managed to win the regional final and we were qualified for the world wide final in Paris. We didn’t win there.

  • This app has never been used in real life, and it wasn’t actually ready for real life anyway for many reasons, the most obvious one is the choice of the platform itself. Also, we were still enrolled in college and we were living in an environment that wasn’t suitable for creating innovative companies.

What I feel from this last point, is that it’s important to be at the right place and at the right moment. In 2007/2008, having a Smartphone that could run rich apps was a big deal and very few devices were capable of offering a correct UX (The HTC Diamond was one of those). I wish we had the possibility to develop a working prototype on Android or iOS and I wish we were in an environment that favorited entrepreneurship and risk taking.

But let’s face it, the execution that Uber made feels just right. The fact that the drivers are requested to obtain a licence from Uber removes all the security issues. The fact that you are required to link your credit card during the subscription and that the price is calculated by the service makes the experience easy for both the driver and the rider, who don’t have to manipulate money anymore.

If you want to see, what is like riding an Uber cab, you can watch this video from Loic Lemeur who is the first Uber user in Paris. I can’t wait to try it one day.  Folks, please, steal my wallet!!

Test your Android app on many devices

A few days ago I saw two tweets from  Pamela Fox where she complained about how hard it is to make an Android application work on all the known devices:

She is right, even by following the best practices published by Google, you never know whether your app will perform the same everywhere until you actually test it on all the hardwares, all the resolutions  and all the Android versions. This fragmentation is what makes programming on the Android platform so hard.

Yesterday I have thought about a possible solution that would rely on Crowdsourcing. This is how it works: Testers register to the platform by listing all the devices they can test the applications on. Then for each test, they would have to answer to a set of simple questions written by the developer(s). Of course, the platform will reward the testers in one way or another (or each developer would reward the testers in their own way). Hopefully some solutions like this one exist like  The Beta Family. To be honest, it doesn’t seem like they have a lot of testers/developers relying on their service and there are certain things that I would do differently (like making sure that the beta can be downloaded immediately).  So it would be interesting to rely on other type of platforms.

In fact there are other cloud based solutions, where different devices are available for your tests on the Cloud. Good examples of these are: Perfecto Mobile and Device Anywhere.  I haven’t used one of these platforms yet, in fact I am not a test freak I just focus on testing on 3 different devices (3 completely different configurations, resolutions and Android versions) and I make sure to follow the best practices to deliver a high quality application. But if you have, please leave a comment and tell us what was your experience like.

Also, please drop comment if you happen to know other platforms/solutions to help solve that particular problem.

Thank you Stanford.

Dear Stanford,

By this blog post, I would like to tell you how much I am grateful to you for putting all these classes online.  First you taught me how to program on iOS from scratch and now you are teaching me AI and Machine Learning.  I am so looking forward to following your different entrepreneurship courses  to start the year off right.

It doesn’t matter why you are doing this, I just wanted to say: Thank you!


Dear Reader,

Turn off the TV, and start taking one or more of these free classes:

Seriously, turn it off!

I am going to DroidconUK!

Remember that last blog post where I talked about an Android event called Droidcon? The next one will take place in London and I am glad to announce that I have kindly been invited, as a Student, to attend this event.

This is very exciting, because:

  • I have never been in London before and it is one of the cities that I wished I could visit long long time ago.

  • Mobile development, especially with Android, is what I have been doing for the last couple of months. It is also what I am going to be focusing on in the future.

  • The quality of the speakers and the talks is very high!

The event will last for 2 days. Day 1 will be reserved for Barcamps where Android developers will gather to talk about different topics chosen by the attendees.  Day 2 is a multi-tracked conference. I HATE (in the positive sense of the term) multi-tracked conferences, I wish I were able to split myself in two in order to be present at different rooms at the same time, but let’s top ranting about this. Let’s make a choice!

This is the program I will be following:

  1. 10:10 : I’ll start the day in Room 2 to attend the Wireframing Like a Pro session given by Greg Taylor. I think this is a great way to start the day. Wireframing is one of the most important things to consider when it comes to designing a new product. I don’t know whether Greg will talk about tools or processes, but in any case I will certainly learn a LOT from his talk!

  2. 10:45 : I think I’ll stay in Room 2 to watch Nick Butcher talk about Excellence in the Android User Experience.  It is clear that a good user experience is crucial for the success of a Mobile application. Think about what all the top notch apps have in common? A good user experience, PERIOD! So hopefully, I’ll learn a bunch of tips form this talk that will help me build better and more successful applications. Finally, this talk is short enough to let me jump over another session when it’s finished.

  3. 11:35 : Room 2 again! Mustapha Isik will talk about building games for the Android platform. Back in 2003, I came into programming (for real) by building games in C++ (most of them were very simple though, Tetris, Snake, PacMan and a few failed attempts to build a RPG).  Although I’m not into this anymore, I’m very curious about what it takes to build games for the Android platform. And who knows this talk may revive the passion that I had for building games!

  4. 12:20 : Let’s move to Room 1 now. Why? Because Mark Murphy himself (same as Chuck Norris but for Android instead of kicking asses), will talk about Traceview and MAT for Fun and Profit. MAT stands for Memory Analyser Tool, which is an Eclipse plugin that helps you reduce the memory consumption for your app and helps you find memory leaks! Traceview is an Android profiler that I tried to use before unsuccessfully as you can see in this StackOverflow question that I asked before. Wait! 130 talented developers took a look at my question and none of them dared to answer? Hopefully, I’ll be able to answer it myself at the end of this talk! Note also that this is where I hate multi-track conferences the most. Because during this talk I’ll be missing another talk about game programming on Android given by Yosi Taguri and a talk about Test Driving Android Apps using Roboeletric given by Joseph Moore from Pivotal Tracker. But hey, c’est la vie !

  5. 15:06 : I stay in Room 1 to attend a talk given by Richard Hyndmann about Android Market for Developers.

  6. I just realized that the dice are already rolled here, since Room 1 hosts the longest talks in duration. However, there is one particular talk that I want to attend which is Massively Scalable C2DM with QoS and SLAs given by Dylan Boyd. So this is obviously about push notifications on the Android platform. I have been using C2DM for one of the projects that I have been working on and it works very well, but I still have a lot of questions about it and I hope this talk will help me answer them. So may be I’ll start moving back and forth from Room 1 to Room 4 starting from 15:40.

This will be very exciting, I can feel it! One last thing, I still don’t know where to sleep there! Do you, dear reader, have any good plan? Youth hostels are cheap but I have never experienced any before. The thing I am worried about is not having a good sleep because of roommates that come in at 4 AM or something. Generally I am not a heavy sleeper, I usually go to bed somewhere between 3 AM and 4 AM and wake up at 9 AM. But this time I want to sleep normal 8 hours in order to be fresh for the conference and for visiting London in good conditions!

Any good plan? Anyone looking for a room as well? May be we could take one BIG room at a youth hostel, for many droidcon attendees that are on a low budget as well, in order to reduce expenses?

Let met know, and I hope to see you soon at Droidcon UK 2011!

ZOMG, Droidcon 2011 London is coming!

As an Android developer (yes for the last 3 months I have been doing a lot of Android development during my internship) there is one hell of a conference where I would love to go and that’s Droidcon. Droidcon, is typically a european based Android conference. Among all these Droidcons, the one happening in London on 6 & 7 of October 2011, is particularly interesting and well… intense!

Why?

Well, first let me tell you about the speakers:

  • Joseph Moore from Pivotal Labs one of the top contributors on the unit testing framework Roboeletric.

  • Richard Hyndman from Google, who I saw last month in Paris where he talked about some good practices that every android developer should must adopt.

  • Mark Murphy, enough said. This guy doesn’t need any presentation I guess, I mean that’s CommonsWare for god sake!

Again, check the entire list of speakers here.

The talks are also various, ranging from very technical presentations (Game development, managing concurrency on multi-core processors devices, unit testing your app) to more generalist presentations (running a private beta on the Android market, Security etc.). The program of the conference can be accessed here.

Of course, we can watch these sessions later or via streaming but nothing can replace a physical presence to the conference where you could actually meet and talk to other developers, exchange ideas, find some business opportunities etc.

To finish, the registration is not that expensive (150£) and I have actually never visited London, sounds like a great occasion to do it!

What do you think? Did you go to Droidcon London 2010, was it worth the commute/money?

Tell me about it!

RubyConf 2010 – ZOMG Why is this code so slow?

In this blog post, I am going to continue what I started earlier. In other terms, I keep watching Ruby & Rails related conferences videos on Confreaks, and summarizing them on my blog. Today, I watched a very interesting talk given by Aaron Patterson (aka @tenderlove) called ZOMG Why is this code so slow?. Aaron is the father of Nokogiry, and he is basically  the only one who is contributing both to Ruby and Rails (where he is the 4th top contributor)! He is also very fun to listen to, very comic but serious about the stuff he is talking about. (he actually reminds me of Scott Hanselman in the .NET world).

So the goal of this talk was to talk about the performance improvements that he made on ActiveRecord while rewriting ARel. Or no, wait! It was about the work he has done on ARel while improving the performances on ActiveRecord. Seems confusing? Actually, it is not. The goal of his talk was to explain how he fixed the performance issues on Rails 3.0.  Rails 3.0 has (or had) performance issues? Turns out, yes! In fact, ActiveRecord was 5 times slower than Rails 2.3! Now things are doing better thanks to his work, but what did he do exactly? Let’s go into that! Summary starts…

What’s ARel?

  • ARel is a Relational Algebra Library. It can handle an AST (Abstract Syntax Tree) and turns into something else. In the context of its integration within ActiveRecord, it turns that AST into a SQL statement.

Are the performance issues related to Ruby?

  • Aaron mentions than even if Ruby is not a super fast language (at least comparing to compiled languages like C), usually the slow is linked to poor code.

When should we make our code faster?

  • When it is not fast enough.

How do we know that it isn’t fast enough?

  • When people start noticing it.

What is the basic thing that we need to do when working on performance?

  • Measuring and benchmarking. In fact measurement is paramount, because it allows us to know exactly how much faster, a chunk of code became after our modifications.

But, what do we need to measure?

  • For the ActiveRecord performance issues, Aaron started thinking about the different stack layers that get called when a user makes a request such as Post.find(id). The stack goes like this:
  1. Post.find(id)

  2. ARel

  3. find_by_sql(id)

  4. execute()

  5. log()

At somepoint, Aaron decided to focus on the 3 top level layers (from find_by_sql to log). He needed to run some benchmarks to know exactly where the performance issues were really occuring. We will get back to that later.

What are the two things that we should optimize for when dealing with performance?

  • Time and space;

What do we need to reduce in our to gain in performance?

  • Method calls.

  • Branching and looping.

  • Objects (memory consumption).

And turns out that when writing a clean code, the things to reduce are exactly the same. Therefore Performant Code == Clean Code.

What tools do we have to run benchmarks?

require 'benchmark'

def fib n
  a = 0
  b = 1
  n.times { a, b = b, a + b}
  a
end

Benchmark.bm(7) do |x|
  x.report("fib") do
    3000.times do |i|
      fib(1000)
    end
  end
end

Which gives the following results:

user     system      total        real
fib      3.740000   0.010000   3.750000 (  4.009678)
  • However this benchmark is not very helpful. It doesn’t give information about how this fibonacci sequence was generated. We need to benchmark through an increasing number of iterations in order to know about the nature of the algorithm that has been used.

For example:

require 'benchmark'

def fib n
  a = 0
  b = 1
  n.times { a, b = b, a + b}
  a
end

Benchmark.bm(10) do |x|
  [1, 10, 100, 1000, 10000].each do |n|
    x.report("fib #{n}") do
      n.times { fib(1000) }
    end
  end
end

  • This has the ability to give us the information that the algorithm runs in a linear time.

  • We also have another tool for benchmarking which is called Minitest/benchmark.

What does minitest add to the game?

Minitest is nice in the sense where it allows us to assert that a given algorithm occurs within a certain class of complexity. For instance we could assert that an algorithms runs in linear time, if someone changes it in the way that it woul run in polynomial time then the assert would fail.

From the previous stack, where did the change happen?

After running benchmarks using the previous tools and after plotting the results, Aaron realized that the changes occured at the log() method.

What do we do then?

  • We need to run method call analysis. To do that we can use Perftools which is a sampling profiler. We can also use Ruby-prof to see the actual number of method calls.

  • In Rails 2.3  2000 method calls of Time#now and Time#allocate were made for every 1000 iterations Vs 4000 in Rails 3.0 beta.

  • After fixing this, things were better but still 2 times slower.

What to do then?

Given that the find_by_sql part didn’t really change between the two version of Rails, ARel was the one that needed to be improved!

First strategy: make superficial improvements!

  • Superficial improvements are useful when we have a limited domain and system knowledge. It allows us to see the results quickly, but we don’t get so much benefits for the time put into it. The superficial improvements that were made are the following:

  • attr_ accessors*

def some_attribute
   @some_attribute
end
# vs
attr_reader :some_attribute
  • The attr_reader is much faster than the method form. The reason behind this is that the way Ruby is built, is that it looks to an AST of code to execute. The C code for the method form is much longer. This code uses vm_setup_method which does:
  1. Check for stack overflow.

  2. Pushing a stack frame.

  3. Copying arguments.

  • #ProTip: if we need to write the accessor method? we can write an alias like this:
class Foo
  attr_reader :some_attribute
  alias :some_attribute? :some_attribute
end
  • Hash Vs Inject

Rubyists tend to write the following code:

some_list.inject({}) do |hash, val|
  hash[val] = some_transform(val)
  hash
end
view raw inject.rb This Gist brought to you by GitHub.

This could be instead written like this:

values = some_list.map { |val|
  [val, some_transform(val)]
}
Hash[values]

Benchmarking these two give the following result:

  • inject is slower than hash + map. The reason is that people are using it wrong, we should use injectonly when one calculation depends on a previous one.

  • This is a better usage for inject():

%w{
Foo
Bar
Baz
}.inject(Object) { |klass, string|
  klass.const_get(string.to_sym)
}
  • Proc Activation
lambda {...} # vs
class Callable
  def call; .. end
end

  • A lambda takes much more longer than a method call does. The reason is because the lambda needs to remember its context.  So Aaron advises us to use lambda only if we care about using a lambda not just because it responds to call.

  • define method

class Foo
  def foo; end
  define_method :bar do; end
  class_eval %{ def baz; end }
end
  • class_eval is about the same speed as the normal method. define method is much longer. define method uses a bloc.

  • Explicit bloc parameters

class Foo
  def explicit & block
    yield
  end

  def implicit
    yield
  end
end
  • Explicit is slower. We are creating a Proc Object and we are paying its cost (garbage collecting this Proc object). The following is a pattern we should follow:
def sometimes_block
  if block_given?
    Proc.new.call
  end
end
sometimes_block { puts "hi" }
sometimes_block
  • Symbol to Proc
@list.map(&:to_i)
# vs
@list.map { |x| x.to_i }

- Symbol to Proc is much slower than just using a bloc. But in 1.9 that’s not true. So we need to know who we target (know your audience).

  • Return value caching
def some_method
  @some_method ||= some_expensive_op
end
  • Here we have extra method calls so it should be avoided as much as possible. Can the caller cache?

  • At the end of these superficial improvements, the performance were better but not as good as they were on Rails 2.3. Aaron needed to go deeper!- After deeper inspections, he noticed that a lot of time was spent at Class#new. A lof time at garbage_collector which means that we create a lot of objects and throw them away.

- He did some Data Structure Analysis (using Graphviz), and he implemented a visitor pattern. The reason for using the visitor pattern is to be able to examine these data structures from the outside.

  • He discovered that the SQL statements generation on ARel had a complexity of n². He knew that SQL generation could be done at a linear time so he decided to rewrite ARel. This decision was supported by the following facts:
  1. There is a clear solution.

  2. Tests are numerous.

  3. Public API is limited.

After 6 weeks of work, the results were encoruaging:

  • SQL statement generation was done at linear time.

  • ARel is now 2 times faster.

  • Adapter specific code is DRY.

He also implemented a new feature on ActiveRecord. Run the following : Model.where("id == xxx").to_dot and admire the graph that is generated and that shows the relation between all the calls that are made :) .

He finally finishes the talk by these two words of wisdom:

- We emphasize the art of code, but we should not forget the science.

- Learn the specific but embrace the generic.

I could not agree more!

As you can see, this talk was very informative and contained many tips about how we should approach performance problems. He introduced some benchmarking tools and explained the process by which he went through to make Rails 3.0 beta as fast as Rails 2.3.