VJS
VJS

Reputation: 2953

java performance front : ref in for loop

Which code is better for the performance point of you? I think second code because ref creation in for loop is not good.

May I know your opinion?

// First Code
for (int i = 0; i < array.size(); i++) {
    SipSession abc = (SipSession) array1.get(i);
}

// Second Code
SipSession abc = null;
for (int i = 0; i < array.size(); i++) {
    abc = (SipSession) array1.get(i);
}

Upvotes: 0

Views: 70

Answers (6)

Mattias Buelens
Mattias Buelens

Reputation: 20179

Never try to optimize without profiling. The JIT compiler does the heavy lifting so you don't have to.

That aside, your array seems to be a raw List instead of a generic List<SipSession>. Generics won't necessarily optimize your code, but it makes it much easier to understand and maintain. Your simple loop could be rewritten as:

List<SipSession> array;
for(SipSession abc : array){
    // Stuff    
}

Upvotes: 0

Narendra Pathai
Narendra Pathai

Reputation: 42005

This would be Micro Optimization and its better to do other kinds of optimizations of code than doing them without proof that it is the bottleneck. Which is not the case here.

Upvotes: 0

NPE
NPE

Reputation: 500913

You should only choose on performance grounds after you've profiled your code and established that this is the bottleneck.

Until you've done that, choose whichever version you think is clearer an easier to maintain.

I would always choose the first version except when I need the last SipSession reference to outlive the loop.

Upvotes: 3

fge
fge

Reputation: 121840

Ultimately it will make no difference. The JIT will optimize that code away to exactly the same thing.

The only difference is the scope, of course.

Upvotes: 1

MrSmith42
MrSmith42

Reputation: 10161

In your first code the VM or even the compiler will simply remove the reference variable, because it is never used within its scope.

It will be optimized to

for(int i=0;i<array.size();i++){
    array1.get(i);    
}

Depending of what is done in the get method the hole loop may be removed while optimization.

If the order the elements are accessed is not important you can also:

for (int i = array.size()-1; 0 <= i ;) {
    SipSession abc = (SipSession) array1.get(i--);
}

This would call array.size() only once instead of in each loop iteration.

Upvotes: 0

Swapnil
Swapnil

Reputation: 8328

I don't think there's much performance difference between the two. Only major difference is the scope of the SipSession reference. But you should try profiling if you care that much.

Upvotes: 0

Related Questions