6

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
}
4
  • 7
    Messure time and check it out. I think it would be faster than posting question here. Commented Oct 22, 2013 at 13:18
  • Duplicate question: stackoverflow.com/questions/229886/… Commented Oct 22, 2013 at 13:18
  • 5
    the answer is a big no. Commented Oct 22, 2013 at 13:22
  • 1
    @reindeer This is not a duplicate of that question. That asks anout memory, this asks about speed. Commented Oct 24, 2013 at 7:27

3 Answers 3

18

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.

Sign up to request clarification or add additional context in comments.

4 Comments

and for Android system, it's same?
Not only the underlying hardware, even the Java bytecode itself has an instruction set for working primarily with int. Using an int in the for loop means a single iinc instruction will do the loop’s increment but when using a byte a four instruction sequence of iload, iconst_1, iadd, i2b, istore is required.
i calculated time difference by System.nanoTime() , the result deviates both sides , btw , you just earned a fan by your answer
Did I say “four”? Even five instructions ;-)
7

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

2 Comments

Good point +1. But when you are pasting from some other link, quote them. I done that now.
That advice is worthless, since JIT will definitely compile the loop into an efficient form.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.