1

此代码完美运行,但不幸的是,由于 Arrays.sort() 比较器,它触发了垃圾收集。

有没有办法做到这一点不会触发垃圾收集?

(注意:此代码已被修改为更加“通用”。实际代码是针对 Android 游戏的,这就是垃圾收集导致的减速成为问题的原因。)

static final byte INCOME = 0;
static final byte INDEX = 1;

public void vSortEmployees() {
    nPaidEmployees = 0;

    for (nIter=0; nIter<MAX_EMPLOYEES; nIter++) {

        if ((employees[nIter].current == true) && (employees[nIter].volunteer == false)) {

            // We have another current and paid employee; add that employee's "amount earned to date" to the list.
            paidemployees[nPaidEmployees][INCOME] = employees[nIter].fGetTotalIncomeToDate();
            paidemployees[nPaidEmployees][INDEX] = nIter;

            nPaidEmployees++;
        }
    }

    Arrays.sort(paidemployees, new Comparator<float[]>() {
        @Override
        public int compare(float[] f1, float[] f2) {
            if (f2[INCOME] < f1[INCOME]) 
                return -1;
            else if (f2[INCOME] > f1[INCOME])
                return 1;
            else
                return 0;
        }
    });

    // Now we have a list of current, paid employees in order of income received.

    // Highest income paid out
    paidemployees[0][INCOME]

    // Second highest income paid out
    paidemployees[1][INCOME]

    // If we need to reference the original employee object, we can:        
    employees[paidemployees[0][INDEX]].getName();
}
4

1 回答 1

1

没有办法始终触发或不触发 GC。GC过着自己的生活。它在您对数组进行排序时运行的事实并不意味着什么。

但是,您可能可以做一些事情。只是不要为比较器使用匿名内部类。你真的不需要这个。使用常规类并将其对象创建为单例。然后就使用这个实例。在这种情况下,排序期间不会在您的代码中创建新对象,并且 GC 可能不会运行。

class FloatArrayComparator implements Comparator<float[]>() {
    @Override
    public int compare(float[] f1, float[] f2) {
        if (f2[INCOME] < f1[INCOME]) 
            return -1;
        else if (f2[INCOME] > f1[INCOME])
            return 1;
        else
            return 0;
    }
};


class SomeClass {
    private Comparator<float[]> floatArrayComparator = new FloatArrayComparator();

    void myMethod() {
         Arrays.sort(myArray, floatArrayComparator);
    }

}
于 2012-09-15T06:15:22.883 回答