In Java 开发者_运维技巧is there a difference in the two loops in the timing:
for (int i=1; i<11; ++i)
{
// do stuff
}
AND
for (int i=100; i<111; ++i)
{
// do stuff
}
The second loop will run 1 more time than the first.
Second loop will be executed one more time than the first one, since 111-100=11 and 11-1=10.
If you use
for (int i=101; i<111; ++i)
{
// do stuff
}
then the result should be the same as the first loop, timing wise. Of course, things will be different if you actually use i
in
// do stuff
part of your code.
There is at least one (micro)difference in the bytecode:
i = 1
will be translated to ICONST_1
, while
i = 100
results in BIPUSH 100
The first is a single opcode, while the second is an opcode followed by an byte which must be loaded and sign-extended to 32 bits. The first is typically more efficient than the second but I think the difference will be insignificant compared to the whole loop (// do stuf
).
The second (for (int i=100; i<111; ++i)
) surely should be preferred instead of:
for (int i=1; i<11; ++i)
{
// do stuff with (i + 100)
}
it's not only slower - adding 100 each interaction - but also less readable IMHO ...
精彩评论