What are the most expensive (both in terms of bytecode and cpu cycles) statements in the Java Programming language?
I would bet that sleep() has to be one of the costliest! ;)
Your question needs more details. One can always write
while(true) {}
and it will burn up CPU cycles endlessly. What types of statements are you talking about?
Anything that involves IO or something that will serialize your code like calls to System.out.
In terms of CPU cycles:
public class Zombie extends Thread {
public void run() {
while (true)
{(new Zombie()).start();}
}
public static void main(String args[]) {
(new Zombie()).start();
}
}
Borrowed and adapted from here, though admittedly not exactly a single statement.
This does not have an easy answer. It depends on your VM and on your underlying hardware. The VM you are using probably compiles your byte code to machine code, so the question would be: what is the most expensive assembly call on your hardware.
Classically the worst was divide in terms of computation. But computation is cheap these days, and memory is far away. So the most expensive calls on modern hardware are memory accesses that miss the cache. Going out to main memory costs 500-1000 CPU cycles.
So a line such as:
x++;
...might take hundreds of cycles, if x has been pushed out the cache. The most common example of this is traversing a linked list that is in memory.
for (ListElement n = ...; n != null; n = n.next()) { n.val++; }
Here the call n.next()
can take 500-1000 cycles each time, because the linked list can be sparsely distributed in system memory.
In any language, you can find out the speed of various statements by doing them lots of times and seeing how long they take. I'm supposing your question is more intelligent than that. For example, in this scenario, A number of tuning steps were performed, and at each step, something else was the major problem.
First step: major time-taker was the equivalent of incrementing iterators. (Fix? Use integer indexes.)
After fixing that, the problem was building linked lists one element at a time. (Fix? Build them all at once.)
After a redesign, the major problem was allocating and freeing storage for objects. (Fix? Re-use used objects.)
At each stage, some problem is the largest. After fixing that (and getting a good speedup), some other problem is the new largest. After fixing that... (and so on, until you can see what the largest problem is, but you can't fix it).
You see, it has almost nothing to do with "which statements are most expensive". If a statement is doing something that you absolutely need done, and you can't find a better way to do it, then by definition it is the best statement for the job.
OP, take a look at the BCEL project, it may be of interest to you, for learning the specifics about Java ByteCode.