Does this code,
for (byte b = 0; b < 100; b++)
{
//some code
}
run faster than this code?
for (int b = 0; b < 100; b++)
{
//some code
}
Does this code,
for (byte b = 0; b < 100; b++)
{
//some code
}
run faster than this code?
for (int b = 0; b < 100; b++)
{
//some code
}
No, not at all; if anything, it will be slower, because the underlying hardware generally has instructions for working with the native "int" type (32-bit two's complement integer) but not for working with 8-bit signed bytes.
Always use an int data type as the loop index variable whenever possible because it is efficient when compared to using byte or short data types. because when we use byte or short data type as the loop index variable they involve implicit type cast to int data type.
check this http://www.precisejava.com/javaperf/j2se/Loops.htm
The correct way to optimize code is to profile and analyze it to find hotspots, i.e. places that take most of the time. These can be (and often are) database or network operations, or a poor algorithm operating on a massive amount of data. When hotspots are found, they can be further analyzed to find out ways to make them faster (modify database queries, use a cache etc.)
Optimization is not deciding whether to use a byte
instead of an int
, or whether to use a StringBuilder
instead of a StringBuffer
. This is known as micro-optimization, which is worthless. Optimization is always context dependent and cannot be performed with general "use X instead of Y" or "always do Z" rules.