Skip to content

Instantly share code, notes, and snippets.

@tomnomnom
Last active December 15, 2015 16:49
Show Gist options
  • Select an option

  • Save tomnomnom/5292044 to your computer and use it in GitHub Desktop.

Select an option

Save tomnomnom/5292044 to your computer and use it in GitHub Desktop.
It seems that when using sort() (i.e. the keys are re-assigned), array access slows down; but with asort() (i.e. the keys are not re-assigned) access speed is not affected.
<?php
const INT_COUNT = 1000000;
// Fill an array with random ints
$ints = [];
for ($i = 0; $i < INT_COUNT; $i++){
$ints[] = rand(0, 255);
}
// Sort the ints
sort($ints);
$start = microtime(true);
// Do nothing but access each int in the array
for ($i = 0; $i < INT_COUNT; $i++){
$ints[$i];
}
$finish = microtime(true);
printf("Time taken with sort(): %.3f seconds\n", $finish - $start);
// Now do it again, but this time use an asort
// Fill an array with random ints
$ints = [];
for ($i = 0; $i < INT_COUNT; $i++){
$ints[] = rand(0, 255);
}
// asort the ints
asort($ints);
$start = microtime(true);
// Do nothing but access each int in the array
for ($i = 0; $i < INT_COUNT; $i++){
$ints[$i];
}
$finish = microtime(true);
printf("Time taken with asort(): %.3f seconds\n", $finish - $start);
// Typical outputs on my machine:
//
// Time taken with sort(): 0.196 seconds
// Time taken with asort(): 0.067 seconds
//
// Time taken with sort(): 0.196 seconds
// Time taken with asort(): 0.071 seconds
//
// Time taken with sort(): 0.201 seconds
// Time taken with asort(): 0.065 seconds
@disjunto

disjunto commented Apr 2, 2013

Copy link
Copy Markdown

This is a strange situation.

What platform and version of php are you using? I'm definitely not seeing this when I run your code.

Time taken with sort(): 0.044 seconds
Time taken with asort(): 0.039 seconds

UPDATE: I have a feeling PHP has some kind of caching being applied, as sort is reindexing everything, the minor cache that exists is being wiped, causing it to access slightly slower. foreach returns the same time no matter what as it iterates instead of references by index (which is the problem)

@nicholasruunu

Copy link
Copy Markdown

sort function note on php.net

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

I believe this is what's causing the slower access.

@robmiller

Copy link
Copy Markdown

I'm quite certain it's the issue @nicholasruunu pointed out: first, because that's the only difference between sort and asort, and second, because changing the for loops to:

foreach ( $ints as $key => $val ) {
    $ints[$key];
}

…results in asort being approximately 25% slower for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment