Convert to a column oriented array in Java

Although I have Java in the title, it can be for any OO language. I would like to learn some new ideas to improve the performance of what I'm trying to do.

I have a method that constantly gets an array of Object []. I need to split the objects in this array into multiple arrays (a list or something else), so I have an independent list for each column of all arrays that the method receives.

Example:

List<List<Object>> column-oriented = new ArrayList<ArrayList<Object>>();

public void newObject(Object[] obj) {
    for(int i = 0; i < obj.length; i++) {
        column-oriented.get(i).add(obj[i]);
    }
}

Note. For simplicity, I omitted the initialization of objects and more.

The code shown above is slow of course. I have already tried several other things, but would like to hear some new ideas.

How would you do this, knowing that it is very sensitive to performance?

EDIT:

I checked a few things and found that:

ArrayList ( ) Object [] . , System.copyArray. ( , ) , ArrayList ...

+3
4

. ? / ( )? .

- . , obj ( ), List . List<Object[]>. . , ( n), m, m n , internalArray.get(m)[n]. - , , ( ).

+2

LinkedList . O (1). ( ArrayList, ).

. N - , 3 * N ref ( LInkedList prevRef/nextRef/itemRef) N ref.

, , , , , .

, !

, ArrayList , ... "":)

0

LinkedList , . , wrappping Object arra addAll .

0

ArrayList - ( , ).

As an alternative solution, you can try just saving the rows first and creating the columns when necessary. Thus, copying the internal arrays in the list is minimized.

Example:

//Notice: You can use a LinkedList for rows, as no index based access is used.
List<Object[]> rows =... 

List<List<Object>> columns;

public void processColumns() {
  columns = new ArrayList<List<Object>>();
  for(Object[] aRow : rows){

    while (aRow.size() > columns.size()){
      //This ensures that the ArrayList is big enough, so no copying is necessary
      List<Object> newColumn = new ArrayList<Object>(rows.size())
      columns.add(newColumn); 
    }

    for (int i = 0; i < aRow.length; i++){
      columns.get(i).add(aRow[i]);
    }
  }
}

Depending on the number of columns, it is still possible that the external list copies arrays from the inside, but regular tables contain much more rows than columns, so it should only be a small array.

0
source

Source: https://habr.com/ru/post/1743332/


All Articles