views:

436

answers:

2

Does the 'instanceof' keyword bear with it a relatively heavier impact on the Android platform (and more speciffically the mobile phones running the Dalvik VM)?

Thank you.

+2  A: 

I do not think instanceof bears a heavier impact on the Dalvik VM opposed to the JVM.

If you have any doubts, you can see for yourself when you run your application with a tool called Allocation Tracker that comes standard as a tool for the DDMS.

Anthony Forloney
That helped thanks.
Michiel
+1  A: 

I found that instanceof is mostly faster (around 60-85% of the time). However this percentage falls when the phone is presented with background activity (e.g. GC, touching, buttons, shaking it etc.) but instanceof remains faster above 50% of the time. When the number of cycles is made very large (i.e. > 1000000) instanceof is nearly always faster. The order in which the two while loops are presented (i.e. first the instanceof loop and then the field check loop) affects the results but instanceof remains the fastest.

        AbstractParticle circleParticle = new CircleParticle();
        int cycles = 100000

        long now1 = System.currentTimeMillis();
        int i = 0;
        while(i<cycles) {
            if(circleParticle instanceof CircleParticle) {
                i++;
            }
        }
        long timetaken1 = (System.currentTimeMillis()-now1);

        long now2 = System.currentTimeMillis();
        int j = 0;
        while(j<cycles) {
            if(circleParticle.type == AbstractParticle.TYPE_CIRCLE) {
                j++;
            }
        }
        long timetaken2 = (System.currentTimeMillis()-now2);

        if(timetaken1 < timetaken2) {
            type1won++;
        }
        else if(timetaken2 < timetaken1){
            type2won++;
        }

        Log.d("instanceof test","type 1 favoured : "+((float)type1won/(type1won+type2won)));        
Michiel
Your sameple is nonsense, i and j are not used after the loop so its highly likely that the loops are omitted from running code as theres no point in running them.
mP
Wise remark, I should check for that; thank you. That leaves me with questions however: how one was consistanly faster and why time taken did increase when 'cycles' increased.I will remember what you pointed out when I'm building tests in the future.
Michiel