Originally posted by Mark Herschberg:
[B]Note: the following questions are with respect to the J2ME APIs, kVM, MIDP, etc. However, I'm not sure how different that implementation is from J2SE in the following issues.
[/B]
This doesn't seem right. In the first case, even if not inlined (which Peter Haggar has pointed out most compilers don't do very often), it should add that much extra overhead.
I'd also find it surprising that the first line of code above is faster. I'm not exactly sure what
String.class does which is so expensive. In the second case, you have the cost of creating a new String (unless it was used elsewhere, and the object already exists in the String constant pool!).
Any thoughts?
--Mark
[This message has been edited by Mark Herschberg (edited September 13, 2001).][/B]
</BLOCKQUOTE>
Hi,
LITERAL VERSION - String.class;
INSTANCE VERSION - "".getClass();
Unfortunatley Henry is right.
The instance version runs
between 10 and 15 times faster than String.class. ( I even ran it with new String.getClass() and this is true)
If you don't believe me try it yourself.
I ran a
test of 10000 iterations for each and "every" time
"".getClass() runs faster.
I would guess that this is because the literal version either has more code overhead or is dynamic(reflection?) in every execution ( I think that's what Henry was saying with
"The compiler generates a mew method which attempts to instantiate the given class"... I could be wrong) where the instance version just reuses compiled code.
The instance version will of course reference the "" String in the literal pool, referencing itself over and over.
This is interesting because it is not intuitive, however I have found no documentation explaining the actual cause of this. I looked through the
Java Language Specification and Java Virtual Machine Spec and couldn't find anything on the .class literals performance. I think I'm going to ask this on in the sun Java forum and see what I get!!!
Anyway, those are my thoughts