You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tinkerpop.apache.org by dkuppitz <gi...@git.apache.org> on 2018/08/25 19:30:58 UTC

[GitHub] tinkerpop issue #920: optmizes collection copy with Collections addAll

Github user dkuppitz commented on the issue:

    https://github.com/apache/tinkerpop/pull/920
  
    I can see why `Collections.addAll(...)` would be faster than `c.addAll(Arrays.asList(...))`, but not why it would be faster than a simple loop. I think if you really want to squeeze out as much as possible, you should prevent the use of lists altogether (ultimately the list is converted back to an array, so there's really no point of dealing with lists there, other than making the code more readable).
    
    Only having arrays could look like this:
    
    ```java
    default GraphTraversal<S, E> hasId(final Object id, final Object... otherIds) {
        if (id instanceof P)
            return this.hasId((P) id);
        else {
            Object[] ids;
            if (id instanceof Object[]) {
                ids = (Object[]) id;
            } else {
                ids = new Object[] {id};
            }
            int size = ids.length;
            int capacity = size;
            for (final Object i : otherIds) {
                if (i.getClass().isArray()) {
                    final Object[] tmp = (Object[]) i;
                    int newLength = size + tmp.length;
                    if (capacity < newLength) {
                        ids = Arrays.copyOf(ids, capacity = size + tmp.length);
                    }
                    System.arraycopy(tmp, 0, ids, size, tmp.length);
                    size = newLength;
                } else {
                    if (capacity == size) {
                        ids = Arrays.copyOf(ids, capacity = size * 2);
                    }
                    ids[size++] = i;
                }
            }
            if (capacity > size) {
                ids = Arrays.copyOf(ids, size);
            }
            this.asAdmin().getBytecode().addStep(Symbols.hasId, ids);
            return TraversalHelper.addHasContainer(this.asAdmin(), new HasContainer(T.id.getAccessor(), ids.length == 1 ? P.eq(ids[0]) : P.within(ids)));
        }
    }
    ```
    
    This is untested and thus not benchmarked, I'm just guessing that it should perform better than the current implementation.


---