I need to do some image manipulation in java. I am porting python code, which uses numpy arrays with dimensions cols, rows, channels; these are floating point. I know how to get RGB out of a BufferedImage and how to put it back; this question is about how to lay out the resulting float image.

Here are some of the options:

1. direct translation:

```java
float[][][] img = new float[cols][rows][channels];

```

2. put channels first:

```java
float[][][] img = new float[channels][cols][rows];

```

3. combine indexes:

```java
float[] img = new float[rows*cols*channels];
img[ i * cols * channels + j * channels + k ] = ...;

```

Option 1 has the advantage that it reads the same as the original code; but it seems non-idiomatic for Java, and probably not fast.

Option 2 should be faster, if I understand how Java N-dimensional arrays work under the hood; at the cost of looking slightly odd. It seems this allocates `channels*cols` arrays of size `rows`, as opposed to option 1 which allocates `rows*cols` arrays of size `channels` (a very large number of tiny arrays = large overhead).

Option 3 seems to be closest to what the AWT and other Java code does; but it requires passing around the dimensions (they are not built into the array) and it is very easy to get the indexing wrong (especially when there is other index arithmetic going on).

Which of these is better and why? What are some of the other pros and cons? Is there an even better way?

**UPDATE**

I benchmarked options 1 and 2, on a non-trivial example of image processing which runs four different algorithms (in a 10x loop, so the VM gets to warm up). This is on OpenJDK 7 on Ubuntu, Intel i5 cpu. Surprisingly, there isn't much of a *speed* difference: option 2 is about 6% slower than option 1. There is a pretty large difference in amount of memory garbage-collected (using `java -verbose:gc`): option 1 collects 1.32 GB of memory during the entire run, while option 2 collects only 0.87 GB (not quite half, but then again not all images used are color). I wonder how much difference there will be in Dalvik?