Performance of primitive data type vs object data type in Java

By xngo on February 21, 2019

Using the object data type instead of its primitive counter part is very expensive. In fact, object data type is approximatively 43 times slower than its primitive counter part. However, I have to scale up to 1 billion iterations to see the difference.

The code

/**
 * Performance of primitive data type vs object data type.
 * @author Xuan Ngo
 *
 */
public class PrimitiveVsObject
{
  public static void main(String[] args)
  {
    long lStart = 0;
    long lEnd = 0;
    int lMaxSize = 1000000000; // 1 billion.
 
    // Primitive data type
    System.out.print("Primitive data type runtime: ");
    lStart = System.currentTimeMillis();
    for(int i=0; i<lMaxSize; i++)
    {
     int test = i; 
    }
    lEnd = System.currentTimeMillis();
    System.out.println(lEnd-lStart);
    // Output: Primitive data type runtime: ~2454
 
 
    // Object data type
    System.out.print("Object data type runtime: ");
    lStart = System.currentTimeMillis();
    for(int i=0; i<lMaxSize; i++)
    {
     Integer test = new Integer(i); 
    }
    lEnd = System.currentTimeMillis();
    System.out.println(lEnd-lStart); 
    // Output: Object data type runtime: ~106593
 
  }
 
}

Github

  • https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/lang/PrimitiveVsObject.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.