JDK-8028422 : Creating uninitialized primitive arrays can boost Java performance
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 7
  • Priority: P4
  • Status: Closed
  • Resolution: Won't Fix
  • OS: generic
  • Submitted: 2013-03-20
  • Updated: 2016-02-25
  • Resolved: 2014-12-03
Related Reports
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
I  suggest  to add

    public static native xxx[] newUninitialziedXxxArray(int size);

set of methods to java.lang.reflect.Array for all primitive types except boolean.  These methods will allow to create uninitialized primitive arrays
when initial element values do no matter. For instance in java.util.Arrays

    public static char[] copyOf(char[] original, int newLength) {
//        char[] copy = new char[newLength];
       char[] copy = java.lang.reflect.Array.newUninitializedCharArray(newLength);
        System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
        return copy;
    }

and many other places all over JDK.


JUSTIFICATION :
Zeroing arrays is expensive. This test

        long t0 = System.currentTimeMillis();
        for(int i = 0; i < 1000; i++) {
              byte[] a = new byte[n];
        }
        System.out.println(System.currentTimeMillis() - t0);

shows < 1ms for n =  1 and ~500 ms for n = 1000000 on my PC. Creating uninitialized arrays will boost performance.


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
java.lang.reflect.Array.newUninitializedXxxArray returns xxx array with uninitialized elements.
Comments
From a security point of view then access to uninitiated memory gives an attacker the ability to read areas of the heap where interesting objects may have once lived. So I don't think this can be exposed as a public API as suggested. That said, there are cases where HotSpot can elide the initialization and there are some optimizations that do that.
15-11-2013

The original post with some estimations for proving the concept is here: http://stackoverflow.com/questions/13780350/is-there-any-way-to-create-a-primitive-array-without-initialization It may be useful to have a way of allocating an uninitialized array of primitive types for the sake of performance. However, more accurate estimation may need to be performed.
15-11-2013