2

I have a collection List and i need to reverse order of it. Everything works fine with

List<Point> myList = new ArrayList<Point>();

i can reverse it with

Collections.reverse(myList); 

but this causes to allocate java.util.AbstractList$FullListIterator

i have about 5000 - 10000 paths to reverse in pathfinder and this causes GC to kick in.

How can i reverse this without any neccessary allocation ? I'm using generic pools whenever i can but i'm stuck with this.


Python dict.setdefault uses more memory?

I was writing some Python code that involved something like this

values = {}
for element in iterable:
    values.setdefault(element.name, []).append(element)

Because I could have sorted the input previously, I also implemented it like this

values = {}

cur_name = None
cur_list = None

for element in iterable:
    if element.name != cur_name:
        values[cur_name] = cur_list
        cur_name = element.name
        cur_list = []
    cur_list.append(element)
if cur_list:
    values[cur_name] = cur_list
del values[None]

Here the input is already sorted by element.name.

The second approach was much faster than the first approach, and it also used less memory.

What's the reason for this?

Or have I made some sort of mistake in the second approach?

4

5 に答える 5

2

もう一度ループする必要がないようにデータ構造を構築すると思います。これで私が言いたいのは..データベースからこれを読んでいる場合は、order by句を使用してください

于 2012-08-16T07:27:30.640 に答える
2

これを試して:

int size = myList.size();
for (int i = 0; i < size / 2; i++) {
    Point temp = myList.get(i);
    myList.set(i, myList.get(size - i - 1));
    myList.set(size - i - 1, temp);
}

これが割り当てるのは Point への 1 つの参照だけなので、あなたの場合は問題ありません。

于 2012-08-16T07:27:55.297 に答える
1

リストの長さを単純にループして、 indexiとで項目を交換できます(n-i-1)。割り当ては必要ありません。

int n = myList.size();
for (int i=n/2; i-->0;) {
    Object o = myList.get(i);
    myList.set(i, myList.get(n-i-1));
    myList.set(n-i-1, o);
}
于 2012-08-16T07:19:02.200 に答える
1

リストの半分のサイズでループを実行すると、これらを交換するようなものになります first-with-last second-with-(last-1) third-with-(last-2) ...so on...

for(int i=0;i<list.size()/2;i++){           
    Object temp=list.get(i);
    list.set(i, list.get(list.size()-(i+1)));
    list.set(list.size()-(i+1), temp);
}
于 2012-08-16T07:33:02.717 に答える
0

ArrayList は絶対に必要ですか?

リバースが唯一の重要なタスクである場合は、それをJava リンク リストに置き換えて、時間と空間の両方でパフォーマンスを向上させることができます。

于 2012-08-16T23:54:24.550 に答える