Question

Case A:

List<String> MyList;
while(index<100) {
    MyList = MyObject.get(MyIndex);
}

Case B:

List MyList;
while(index<100) {
    MyList = (List<String>) MyObject.get(MyIndex);
}

Which of the above would be faster?

In case B, I assume that dynamic casting happens throughout the loop. So, it was my assumption that second could be slower then the first one.

Please say which one could me more faster ?

Was it helpful?

Solution

Java generics is a compile time abstraction. There is no evidence of them is left in bytecode. They just simplify development, but do not affect performance. In the bytecode your first sample of code would look like exactly the same as the second one. Javac will just insert casting for you.

OTHER TIPS

Both should be identical in performance. The first version does create a JVM cast instruction, but it's implicitly added by the compiler. In both cases, the runtime operation is a cast to List. The generic type isn't preserved at runtime.

You can verify this by checking the bytecode, which should be identical in both versions.

First of all Generics is a compile time feature. Java run time has nothing to do with generics. I suggest you to go with Case A, because you are always sure that List will only hold String objects and nothing else. This will help you to avoid ClassCastException at runtime, because you are always sure that the List will contain only String objects and nothing else.

I think both approaches will take same execution time, as the List object known to the java run time in both the cases is same (List MyList;). In case A : List MyList; will be passed as List MyList to JVM, which is same as Case B.

Once you got the byte code for the both of them you'll see that both are same . So there is no change of performance in both of them .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top