5

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
}
bedwyr
  • 5,774
  • 4
  • 31
  • 49

3 Answers3

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.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • 1
    and for Android system, it's same? –  Oct 22 '13 at 13:24
  • 4
    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. – Holger Oct 22 '13 at 13:47
  • i calculated time difference by System.nanoTime() , the result deviates both sides , btw , you just earned a fan by your answer – Hussain Akhtar Wahid 'Ghouri' Oct 22 '13 at 13:51
  • Did I say “four”? Even five instructions ;-) – Holger Oct 22 '13 at 14:01
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

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
Bharath R
  • 1,491
  • 1
  • 11
  • 23
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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121