Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Performance: Strings vs. Enums vs. Static Final Ints

Parts of this have been asked on SO before, but I'm yet to find much in the way of solid evidence and/or a decisive answer.

When passing information around Android in a Bundle, what (if any) performance increases/decreases can be observed by using strings, enums or static final ints?

To give an example use case, there are several times in my app where a certain fragment is loaded and displayed. Each time the fragment is loaded, a Bundle is passed to it containing two arguments: an ID of the data is is showing, and a mode to dictate how to show it. I have a custom state pager adapter set up doing all the heaving lifting, but the crux of the question is here: which (if any) of these would offer any performance gains/losses:

Bundle args = new Bundle();
args.putInt("ID", 1);

// method 1
args.putString("MODE", "Mode1");

// method 2
args.putSerializable("MODE", ModeEnum.Mode1);

// method 3
public static final int MODE_1 = 1; // this would be elsewhere in a constants class
args.putInt("MODE", MODE_1);

In the fragment, the mode is checked in several places, so I'm concerned with which of the three options is more efficient to store in the bundle, and which is more efficient to be compared on the other end.

Any advice, observations or experiences will be greatly appreciated!

like image 595
Mark Ormesher Avatar asked Jul 29 '14 18:07

Mark Ormesher


1 Answers

Okay, so I did some research online and I found information that was either vague, unreliable or contradictory - in short, I didn't find an answer. So instead, I set up a little app to actually test this for myself.

The app passed 200 items in a bundle from one activity to another, then used those values for a mix of comparisons and lookups from arrays and maps. It then repeated this another 9,999 times.

With 10k revolutions of this process, ran several times for each of the three methods, I came to a conclusion:

It doesn't really matter which one you pick.

The differences in performance are tiny, and I mean miniscule. Strings lost the race most of the time by a slim margin, but ints and enums were both top contenders, and sometimes strings beat them both anyway.

The differences in memory consumption were just as narrow. As long as your string values aren't paragraphs of text, the differences are honestly too small to care about. We're talking an increase of a few percent.

Summary:

Sure, if your app is passing around thousands of Bundle values all the time*, then it might be worth optimising it with ints or enums (whichever comes most naturally to your codebase). But otherwise, any increase you get simply isn't worth the effort it would take to create it.

*If you're doing that, you probably know about this already, or there's something wrong in your app's infrastructure!

like image 89
Mark Ormesher Avatar answered Nov 18 '22 09:11

Mark Ormesher