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?
-
Why would you thing it bears a heavier impact in Android opposed to Java?Anthony Forloney– Anthony Forloney2010-02-13 23:14:12 +00:00Commented Feb 13, 2010 at 23:14
-
4Anthony, because it's a completely different VM, register-based rather than stack-based?Matthew Flaschen– Matthew Flaschen2010-02-13 23:20:02 +00:00Commented Feb 13, 2010 at 23:20
-
Why would instanceof create trash ? instanceof tests if an object is an instance of some type it does not involve method invocation or object creation. Why are you asking a nonsense question, joining unrelated VM concepts that do not make any sense ?mP.– mP.2010-02-21 08:47:29 +00:00Commented Feb 21, 2010 at 8:47
-
1"Why are you asking a nonsense question" I can't know that I do until after the fact right? I have removed it from the original post for the sake of nonsenselessness.Michiel– Michiel2010-02-21 11:49:50 +00:00Commented Feb 21, 2010 at 11:49
-
3@mP. Android is notoriously bad at reflection. So naturally Michiel was asking if there's any performance hit using instanceof, since they are somewhat similar. It's not a stupid question at all.phreakhead– phreakhead2013-03-05 18:27:37 +00:00Commented Mar 5, 2013 at 18:27
Add a comment
|
2 Answers
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)));
2 Comments
mP.
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.
Michiel
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.