1

I am Android developer and not new to Java but I have some questions about best practices for performace. Ill give some examples from my code so you can decide.

String concatenation

url = "http://www.myserver." + domain + "/rss.php?"
+ rawType + rawCathegory + rawSubCathegory + rawLocality
+ rawRadius + rawKeyword + rawPriceFrom + rawPriceto;

As far as I know, this would create 11 string objects before my url variable is created, right?

Ive been taught to use StringBuilder, but my question is, whats the minimum amount of strings to concat to make it efficient? I think it wouldnt make much sense to use it concat two strings, right?

Local variables

Sometimes I try to "chain" method calls like so

FilterData.getInstance(context).getFilter(position).setActivated(isActivated);

to naively avoid variable allocation, but is it any faster than this?

FilterData filterData = FilterData.getInstance(context);
Filter filter = filterData.getFilter(position);
filter.setActivated(isActivated);

I believe it should as I save myself a local variable, but it becomes unreadable if the method names are long, etc.

Loops

http://developer.android.com/training/articles/perf-tips.html says that enhanced for loops is 3x faster than the regular for loop, well that great and its easier to write anyways, but, what if I need the index? As far as I know, in enhaced for loop I need to keep track of it myself, like this

int index = 0;
for(Object obj : objects) {
    // do stuff
    index++;
}

Is this still faster than the regular loop?

for(int i = 0; i < objects.size(); i++) {
   // do stuff
}

I think that enhanced for loop maybe does optimisations about that limit, so maybe if the size() got optimized to this

int size = objects.size();
for(int i = 0; i < size; i++) {
   // do stuff
}

How would that stand?

Thanks, I know this might be nitpicking and not make that much of a difference, but Ill rather learn such common tasks the right way.

1
  • Unless you notice your code being slow, don't sweat the small stuff. Don't prematurely optimize, especially if it makes the code less readable. Commented Feb 26, 2013 at 19:39

1 Answer 1

1

Strings:

Unless there's a loop involved, the compiler is clever enough to do the concatenation for you in the best way.

When you're looping, use StringBuilder or Buffer.

Local Variables:

The two examples you give are identical. The memory still needs to be allocated even if you never give it a name.

Loops:

Depending on the type of loop, using enhanced loops can give a massive or negligible improvement, it's best to read up on the one you're using.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.