collection icon indicating copy to clipboard operation
collection copied to clipboard

AbstractSet::add() Performance Optimization

Open jmwebservices opened this issue 4 years ago • 0 comments

AbstractSet::add() is slow for large collections.

AbstractSet::add() internally invokes AbstractCollection::add() which forwards to AbstractSet::offsetSet(). This flow causes AbstractCollection::contains() to be invoked twice which, for extremely large collections, can significantly impact performance.

Background/problem

Proposal/solution

Alternatives

Additional context

$tests = 10000;

$addCollection       = new Ramsey\Collection\Set( 'int' );
$offsetSetCollection = new Ramsey\Collection\Set( 'int' );

$addTime = microtime( true );
for( $i = 0; $i < $tests; ++$i )
	$addCollection->add( $i );
$addTime = microtime( true ) - $addTime;

$offsetSetTime = microtime( true );
for( $i = 0; $i < $tests; ++$i )
	$offsetSetCollection[] = $i;
$offsetSetTime = microtime( true ) - $offsetSetTime;

// ~98% slower
var_dump( ( $addTime - $offsetSetTime ) / $offsetSetTime * 100 );

jmwebservices avatar Sep 26 '20 05:09 jmwebservices