3

给定一个实例,将 的大小增加1 倍以使新元素是原始元素的副本并与原始数组交错List的最有效方法是什么?Listf

例如

f        = 2
Original = [a,b,c,...,x,y,z]
New      = [a,a,b,b,c,c,...,x,x,y,y,z,z]

我目前的实现是这样的:

List< Foo > interleave( List< Foo > original, int f ) {
    int newSize = original.size() * f;
    List< Foo > interleaved = new ArrayList< Foo >( newSize );

    for( Foo foo : original ) {
        for( int j = 0; j < factor; j++ ) {
            interleaved.add( new Foo( foo ) );
        }
    }
}

问题是我的原始列表可能很大,所以性能不是很好。我有一种预感,有一种更有效的方法可以做到这一点;有没有人有什么建议?

4

3 回答 3

1

您提供的代码经过了很好的优化,但是可以进行一些改进;重要的取决于您的确切需求。


首先,如果您的克隆元素将保持与原始元素相同的值,或者只有少数元素(与总数相比)将更改其值,您可能需要考虑基于引用的克隆当前的“真正克隆所有”代码,如果不是一种完全不同的方法,甚至不会创建新列表。

    /**
     * PROS:
     * -Very low memory-footprint, as no new objects are created in memory, just references to a single (original) object.
     * -Can be done with generalization; A single method will function for most classes and data-types, as is below.
     * 
     * CONS:
     * -If you need each clone element to be changed independently from eachother and/or the orininal, this will not work directly,
     * because any change to an reference-element will apply to all other reference-elements that point to that same Object.
     * 
     * @param <E> Sub-class generalizator. Used so that the returned list has the same sub-class as the source.
     * @param list Source list. The list containing the elements to be interleaved.
     * @param f The factor to interleave for. In effect, the number of resulting elements for each original.
     * @return A list containing the interleaved elements, with each element being a REFERENCE to the original object.
     */
    public static <E> List<E> interleaveByReference(List<E> list, int f) {
        List<E> interleaved = new ArrayList<E>(list.size() * f);
        for (E obj : list) {
            for (int i = 0; i < f; i++) {
                interleaved.add(obj);
            }
        }
        return interleaved;
    }

如果您只需要几个克隆来更改值,则交错列表基于引用可能会更好,并且需要更改的元素稍后单独替换。

但是请注意,这种方法的有效性在很大程度上取决于需要更改多少原始列表元素;而且,如果需要更改太多,这种方法虽然在内存占用方面仍然更好,但速度性能会更差(这似乎是您主要关心的问题)。

“稍后单独克隆”可以通过类似的方式实现:

public static void replaceWithTrueClone(List<String> list, int objIndex) {
    list.add(objIndex, new String(list.get(objIndex)));
    list.remove(objIndex + 1);
}

//OR

public static void replaceWithNewObject (List<String> list, int objIndex, String newObject) {
    list.add(objIndex, newObject);
    list.remove(objIndex + 1);
}

如果在程序执行过程中每个元素中的大多数都将具有独立的值,那么您当前的方法已经非常准确了。

有两个可以改进的地方。直接在代码中显示会更容易,所以这就是我要做的:

    /**
     * PROS:
     * -Each element is an independent object, and can be set to independent values without much of an effort.
     * 
     * CONS:
     * -Each element has it's own allocated memory for it's values, thus having a much heavier memory footprint.
     * -Is constructor-dependent, and thus cannot be generalized as easily;
     * Each different expected class will probably need it's own method.
     * 
     * @param list Source list. The list containing the elements to be interleaved.
     * @param f The factor to interleave for. In effect, the number of resulting elements for each original.
     * @return A list containing the interleaved elements.
     * For each of the original elements, the first is a REFERENCE, and the other are CLONES.
     */
    public static List<String> interleaveByClone(List<String> list, int f) {
        List<String> interleaved = new ArrayList<String>(list.size() * f);
        for (String obj : list) {
            interleaved.add(obj); //The first element doesn't have to be cloned, I assume.
            //If it has to be cloned, delete the line above, and change 'i=1' to 'i=0' on the line below.
            for (int i = 1; i < f; i++) {
                interleaved.add(new String(obj));
            }
        }
        return interleaved;
    }

    /*
     * What was changed from the original is commented below.
     */

    public static List<String> original(List<String> original, int factor) {
        /*
         * It is unnessessary to have this 'newSize' variable. It gets needlessly maintained until the end of the method.
         * Although the impact is unworthy of measurement (negligible), it still exists.
         */
        int newSize = original.size() * factor;
        List<String> interleaved = new ArrayList<String>(newSize); //Just do the '*factor' operarion directly, instead of 'newSize'.

        for (String foo : original) {
            /*
             * If you can use the original here, that's one less cloning operation (memory-allocation, etc...) per original element.
             * A low-impact optimization, but still a good one.
             */
            for (int j = 0; j < factor; j++) {
                interleaved.add(new String(foo));
            }
        }
        return interleaved;
    }

使用包含 200 万个元素的原始列表和 2 倍的因子,我在 10 次运行中得到以下平均速度:

  • 创建并使用 2000000 个不同元素填充原始列表需要 6030 (~) 毫秒。
  • 将列表与方法交错需要 75 (~) 毫秒 interleaveByReference()
  • 将列表与方法交错需要 185 (~) 毫秒 interleaveByClone()
  • 将列表与方法交错需要 210 (~) 毫秒 original()
于 2012-08-29T19:49:29.800 回答
1

这可以很好地工作,而无需花费完全复制。

List< String > interleave(final List< String > original, final int f ) {
    final int size = f * original.size();
    final List<String> originalCopy = new ArrayList<String>();
    for (String each : original) {
        originalCopy.add(new String(each)); // <=== duplicate here.
    }
    return new AbstractList<String>() {
        @Override
        public String get(int index) {
            return originalCopy.get(index / f);
        }

        @Override
        public int size() {
            return size;
        }            
    };
}

测试

System.out.println(interleave(Arrays.asList("a", "b", "c"), 2));
System.out.println(interleave(Arrays.asList("x", "y"), 3));

输出

[a, a, b, b, c, c]
[x, x, x, y, y, y]
于 2012-08-28T16:18:38.080 回答
0

通过重新插入原始元素并仅创建副本可以实现较小的加速:

List< Foo > interleave( List< Foo > original, int factor ) {
  int newSize = original.size() * factor ;
  List< Foo > interleaved = new ArrayList< Foo >( newSize );

  for( Foo foo : original ) {
    interleaved.add( foo );
    for( int j = 1; j < factor; j++ ) {
        interleaved.add( new Foo( foo ) );
    }
  }

  return interleaved;
}
于 2012-08-29T07:24:01.640 回答