Speed of iterating through 1-dimensional vs 2-dimensional arrays - java

I was reading a post on how iterating through a 2-dimesional array horizontally is faster than vertically because of the way the data is stored(See:Fastest way to loop through a 2d array?). That made sense when I read the answer but it got me wondering what the difference was between 2 and 1 dimensional arrays. Is there any speed difference in iterating 1-dimension vs 2-dimension arrays with the same number of cells?

On Java, there are many more factors and more overhead with arrays. As arrays are objects, int[][] is an array of array objects of ints. This may make horizontal iteration faster than vertical if hotspot optimizes or caches the array access.
For one vs two dimensional, one-dimensional would be faster as it's an array lookup and a primitive vs an array lookup, a dereference of a reference of an array object, and then a lookup in that array.
However, such microoptimization is not necessarily the best use of your time, as there are likely better places for improvements.

Related

If I create an array that can hold 10 objects, is it possible for that array to less then 10 objects?

I need to create an array that can hold 10 objects. If I make this array will it be able to hold less then the 10 object. An example would be the array has 7 objects and room for 3 more. Is this possible?
Yes. Assign null at some indices. Also, you can create the array without any objects stored in it, specifying the length.
Yes. Arrays can hold any number of items up to, but not including the length you have allocated for it. In Java, arrays of primitive types (int, bool, double, char, etc.) will be filled with the default value of that type for any non-initalizer-list array, and null references for any arrays of Object types.
However, questions like yours are more suited for classroom discussion, as you may still be learning computer science material, it seems like.
It depends on what you mean.
All arrays have fixed length, and each always contains a number of elements exactly equal to its length. In that sense, no, arrays cannot have excess capacity; they are always completely filled. You can, however, keep track externally of which elements contain valid data, and ignore the others.
Technically, no array contains objects, but many contain references (of various types; as opposed to primitive values). It is conventional to be a bit sloppy with our language by calling those arrays of objects, and that's how I interpret the question. The distinction becomes important, however, when we recognize that any element of an array of references may contain the value null, which does not refer to an object. Thus, an array of references with some elements null refers to fewer actual objects than its length. You might characterize that as the array containing fewer objects than its length.
Note that null elements are not limited to the end of an array. They may appear at any index, interspersed with non-null elements.
With all that said, however, I suspect you're looking for Lists, and specifically java.util.ArrayList. Lists are more flexible than arrays in many ways, including that they have adjustable size. And ArrayList indeed does have a distinction between its current capacity and its current size, though the capacity is expanded as needed, not fixed like an array's length. The class name reflects that it is implemented with use of arrays, and its performance characteristics reflect that.
Array is a data structure which stores a fixed-size sequential collection of elements of the same type. When you initialize an array, it can have at most the till the size of array, so for your answer it can have empty cells.
I need to create an array that can hold 10 objects. If I make this array will it be able to hold less then the 10 object. An example would be the array has 7 objects and room for 3 more. Is this possible?
In short, yes. It will be able to hold 0 to 10 objects. However it doesn't mean your array can shrink and grow from 0 to 10. It will be a fixed size of 10 (be it you are using it or not).
The long answer is, there will always be 10 elements populated with some values (be it you are actively using all elements or not). Those elements which you think you are not using at the moment will still be populated with default value according to the data type of the array (i.e. null of object, 0 for integer, false for boolean).
For example, creating an int array of size 10:
int array[] = new int[10];
By default, you will already have 10 arrays (all populated with default 0).
Index: 0 1 2 3 4 5 6 7 8 9
Array: [0][0][0][0][0][0][0][0][0][0]
You will always have these 10 elements at your disposal. It is now up to you how you want use these 10 elements.
If you are looking for something that can shrink and grow. You can look into using java.util.ArrayList which can shrink/grow as you remove/add items into the list.

Storing multiple vectors

I have around 1,700 vectors in the form of:
a*x + b*y + c*z
I need to store it inside a memory structure in Java. So far, my idea was either store the data:
Inside 2-dimensional arrays
Inside lists that hold arrays of 3 values
What would be the optimal move here ?
The best choice would be the one that you can prove the best. This means that when dealing with such questions you should profile different solutions and see which one is better with respect to your pattern of utilization of data.
I see multiple different choices:
have a class Coefficient { double a, b, c; }
use a List<double[]>
use a double[][]
Probably the worst choice would be to wrap them into Double objects since it would place a lot of overhead everywhere.
My guess is that double[][] should be slightly the more efficient because JVM has native instructions to manage array but you won't get the same performance benefit you'd get from other languages because a bidimensional array in Java is still an array of arrays, so it's not contiguous in memory.
Probably List<double[]> and double[][] behave in a quite similar way with respect to reading or updating the values but things may change if you have a lot of insertions or deletions (assuming you resize the list to correct size before adding elements).
In the end just profile the code and check the results.

How C#/Java stores 2D array, it's different with C++?

As I know, C++ stores array by putting 2D array values on a block of memory (continuous virtual memory?), which are fast for accessing value by index.
I came out this question after reading this, "using nested array to store 2D grid is efficient in C/C++, but in Java or other memory-managed languages, doing that will actually give you an array of rows where each element is a reference to the array of columns, which may not be as memory-friendly as you'd like".
Does "a reference to the array of columns" mean they actually be stored in many tiny blocks on memory?
Update
Sorry my question should be "If Java store 2D array on many tiny blocks, how is this easy for 'memory-management'"?
In an MxN matrix, it has M references for N arrays. And that is the reason that in C you must tell the second dimension when you want to pass an array as a function argument, and in Java you dont have to.

How can I change the length of an array? [duplicate]

This question already has answers here:
Java dynamic array sizes?
(19 answers)
Closed 8 years ago.
So I am assigned with a project where I have an array and as the user puts elements into this array it will have to double in length once it gets full. We are not permitted to use array lists or anything in the collections interface. What I was trying to do was to make a new array once the old one was full, and then I would copy the values over to the new array. The problem is I don't know how many times I will have to make a new array, so I was wondering how to go about solving this.
Arrays are fixed length. If you want a data structure that has variable length use an ArrayList
Since the poster explicitly stated the requirements of the homework exclude the use of Collections an alternative approach would be to use System.arraycopy(). In such an approach you only maintain a single array and as you add items to it you use System.arraycopy() to copy the old array into a new larger array. System.arraycopy() is relatively fast and is actually how ArrayList expands its size.
If you are concerned about the cost of using System.arraycopy() you could use it only when your array is full and create a new array with more space. E.g.
Create and array of size 20. When it gets full copy it into and array of size 40. When that gets full copy it into an array of size 60...
Interestingly ArrayList increases its size by
int newCapacity = (oldCapacity * 3)/2 + 1;
when the old array is full. Presumably the writers of this put some considerable thought into how much to grow the array by when needed. It might be worth doing the same.

how to present a 2d array in an 1d array with a size of height or width

I have the problem that I want to do parallelization with Android Renderscript. For this I have to allocate my input data to renderscript and allocate them back. I want to do big matrix multiplications with the size of 8x8 or 64x64 matrices. There are two problems:
1) I cannot allocate two dimensional arrays.
2) forEach executes the loop as often as the size of the allocation. E.g. The input vector has 10 elements the loop will be executed 10 times.
To find a solution I did coding. So my matrix is generated randomly in a byte array. This byte array will be coded row or column to an integer array. So I put a 2d array in a one dimensional array with the size of the length. On the other side (Renderscript) I have to decode them, calculating the result and put the back with the allocation. I want to avoid the coding and to speed up the application. Someone know a better solution for my problem?
array[a][b] --> vector[a] or vector[b] but not vector[a*b] Exist there a possible solution?
I'm not sure that I fully understand your problem.
Let me try to make a general suggestion based on what I understand.
You can create a wrapper class that transform input index to the internal index via getters and setters, this wrapper can also implement java.lang.Iterable.
To help with the second part of your problem, bind the matrix Allocations to the Renderscript separately and pass rsForEach another Allocation that is sized to the number of operations you want to perform. You can use values set in this Allocation and/or the x argument of the root() function to help you find where to operate on the matrix data.
My answer for operating per row/column of an image gives more details.

Categories