Domanda

What is the difference between using a Guava Table implementation and a 2D array if I know the size of the array beforehand?

Is one more efficient than the other? How? Would it make a difference in running time?

È stato utile?

Soluzione

The most obvious and crucial difference is that an array is always indexed, with ints, whereas a Table can be indexed with arbitrary objects.

Consider the Table Example from the Guava site:

Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
weightedGraph.put(v1, v2, 4);
...

The indexing here happens via Vertex objects. If you wanted to do the same with an array, you would have to add some getIndex method to the Vertex class, and accesss the array like this

double array[][] = new double[4][5];
array[v1.getIndex()][v2.getIndex()] = 4;

This is inconvenient and particularly hard to maintain - especially, when the indices may change (or when vertices have to be added/removed, although you mentioned that this is not the case for you).

Additionally, the Guava table allows obtaining rows or columns as separate entities. In a 2D array, you can always access either one row or one column of the array - depending on how you interpret the 2 dimensions of the array. The table allows accessing both, each in form of a Map.


Concerning the performance: There will be cases where you'll have a noticable difference in performance. Particularly when you have a large 2D array of primitive types (int, double etc), and the alternative would be a large table with the corresponding reference types (Integer, Double etc). But again, this will only be noticable when the array/table is really large.

Altri suggerimenti

Additionally to what Marco13 said, read this: https://stackoverflow.com/a/6105705/1273080.

Collections are better than object arrays in basically every way imaginable.

The same applies here. A 2D array is a low-level tool that might be needed when you need some high-performance structure for primitives. However, arrays have no meaningful methods, no behaviour, no nothing, and therefore are usually an underlying data structure in classes that add some behaviour to them. Do this with a 2D fixed-size array and you'll end up with ... a Guava-esque Table.

Also, a Table can be a 2D-array, or a Map<R, Map<C, V>>, in the future we might also have resizable Table implementations - all within one interface.

Regarding the performance - you should almost always go for the more high-level approach to get code as readable and clear as possible, then measure the performance and only if it's problematic, go for different approaches.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top