Efficiency of the way comparator works

前端 未结 2 2005
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 08:21

I am trying to use a comparator to help sort a list of objects. I have a question about how exactly the comparator works and what it would be doing exactly in the following

2条回答
  •  [愿得一人]
    2021-01-06 09:04

    On average, your sort algorithm will call complexOperation() method about log2N times for an array of N students. If the operation is really slow, you may be better off running it once for each student. This could bring an order of magnitude improvement for an array of 1,000 students.

    However, you do not have to do it explicitly: you could make complexOperation(...) store the result for each student, and then return the cached value on subsequent requests:

    private Map cache = new HashMap();
    
    private int complexOperation(Student s) {
        // See if we computed the rank of the student before
        Integer res = cache.get(s);
        if (res != null) {
            // We did! Just return the stored result:
            return res.intValue();
        }
        ... // do the real computation here
        // Save the result for future invocations
        cache.put(s, result);
        return result;
    }
    

    Note that in order for this approach to work, Student class needs to implement hashCode and equals.

提交回复
热议问题