1

I have an array of 6 elements. Is it more efficient (time-wise) to set those elements to null, or to create a new array? I'm going to be using this array hundreds of times.

4
  • 1
    why do you need to set null or create new array? please describe more Commented Apr 2, 2014 at 14:44
  • 3
    if in doubt: measure. My guess is that creating a new one is more efficient. And my guess is that if you only create 100s of arrays, you won't notice the difference. Commented Apr 2, 2014 at 14:44
  • Okay, thanks that makes sense. What is around the maximum number of objects/arrays I can create before running out of space on the stack? Commented Apr 2, 2014 at 14:48
  • Duplicate: stackoverflow.com/questions/4208655/… Commented Apr 2, 2014 at 14:55

5 Answers 5

6

I would use this method.

System.arraycopy

It is native and pretty efficient.

I would keep an array of nulls and copy it into my array using this method, each time when I want to reset my array. So my advise would be not to create a new array each time, but also not to loop (using Java code) and set the elements to null yourself. Just use this native method which Java provides.

import java.util.Arrays;


public class Test056 {

    public static void main(String[] args) {

        String[] arrNull = new String[10000];
        String[] arrString = new String[10000];

        long t1 = System.nanoTime();

        for (int i=0; i<10000; i++){
            System.arraycopy(arrNull, 0, arrString, 0, arrNull.length);
        }

        long t2 = System.nanoTime();

        System.out.println(t2 - t1);

        long t3 = System.nanoTime();

        for (int i=0; i<10000; i++){
            Arrays.fill(arrString, null);
        }

        long t4 = System.nanoTime();

        System.out.println(t4 - t3);
    }

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

15 Comments

@assylias No... Basically I advise not to create a new array each time.
Or Arrays.fill(myArray, null); would be better
@staticx System.arraycopy is a native method, an optimized one AFAIK. Have you seen what the code of Arrays.fill does? Not only does a trivial loop but before that does a few checks. How is it going to be better?
You don't need to have an array of nulls hanging around. You can just efficiently assign null to every position of the array.
But that's just not true IMHO. Updated my answer with an example. Arrays.fill is about 3-4 times slower, it seems.
|
3

Mu - You are not asking the right question.

Do not worry about the efficiency of such trivial operations until it is a known performance bottleneck in your application.

You say you will be nulling/creating 6 references 100s of times. So, you will be creating/nulling/looping < 6000 references. Which is trivial in modern programming.

There are likely much better places where you should be spending your development time.

Comments

1

Creating a new array should be more efficient time-wise because it would only allocate empty references.
Setting the elements to null would imply walking through the entire array to set references to null (which is default behavior on array creation) which is more time consuming (even if for an array of 6 elements it's totally negligible).

EDIT : time-wise is bold because memory-wise is may not be your best option. Since you'll be creating new references, if you instantiate new object, make sure the object of your previous array are garbage collected properly (again, with only 6 elements it must be gigantic objects to see any bad performance impact).

7 Comments

Isn't that exactly what is being done when you set each value of the array equal to null?
Well then why would this be more efficient if they do the same things under the covers? See for example this answer on a related question: stackoverflow.com/a/9314345/1864167
Zero-ing an array is a lot more efficient than creating a new array because the JLS will require the new array to be zero-d anyways.
Jeroen : sorry misread your question. staticx : The new array will only creates null references so I think it's the fastest you can get.
Looks like yours is fastest. ideone.com/a276aV .. I didn't try it with actual data though
|
0

The following bit of code demonstrates that it's faster to assign each value to null.
Note that this is valid for arrays with 6 elements. Eventually it may be faster to create a new array.

    Object[] array = new Object[6];

    long start = System.nanoTime();

    for(int i = 0; i < Integer.MAX_VALUE; i++){
        array[0] = null;
        array[1] = null;
        array[2] = null;
        array[3] = null;
        array[4] = null;
        array[5] = null;
    }
    System.out.println("elapsed nanoseconds: " + (System.nanoTime() - start));
    int length = array.length;

    start = System.nanoTime();
    for(int i = 0; i < Integer.MAX_VALUE; i++){
        array = new Object[6];
    }
    System.out.println("elapsed nanoseconds: " + (System.nanoTime() - start));
    length = array.length;

and the output:

elapsed nanoseconds: 264095957
elapsed nanoseconds: 17885568039

13 Comments

In your case most of the time is probably taken by the GC which would not be that significant in OP's case of 100s of arrays. Interesting anyway
If you repeat this test by changing Integer.MAX_VALUE to 1000 to reflect the actual usage, both times drop to 0.
@staticx, thanks. I've fixed it using nanoseconds. (but not that the high number of iterations reduce the error produced by the currentTimeMillis method).
I am not clear on the mechanics of the loop there, but if you do a simple assignment (not up to Integer.MAX_VALUE), the assignment itself is faster. Because you keep re-assigning a new array of Object size 6 up to Integer.MAX_VALUE when all you need to do is array = newArray. There is no need for the second loop.
The loop is repeating the operation. (You might have misread the code?)
|
-4

The best and secure way to create an array is the next one:

List<Object> myList = new ArrayList<Object>(0);

So can can regenerate by this way the array each time you want. You don't need to set to null. By this way, the array is destroyed and regenerated in memory.

You can read more info in Oracle Java documentation:

3 Comments

array!=List. Just because it's named ArrayList, this doesn't mean it is an array
ArrayList is one of the two possible List implementations: docs.oracle.com/javase/tutorial/collections/implementations/….
Yes, but we are talking about arrays, not lists.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.