I'm wondering. Is there a better performance with this:
$value = preg_replace( array('/_{1,}/', '/-{2,}/'), array('_', '-'), $value);
than this:
$value = preg_replace('/_{1,}/', '_', $value);
$value = preg_replace('/-{2,}/', '-', $value);
This is just a very simple example.
An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows. It creates a new Array and copies every element from the old one to the new one.
The array is faster in case of access to an element while List is faster in case of adding/deleting an element from the collection.
An array is faster than a list in python since all the elements stored in an array are homogeneous i.e., they have the same data type whereas a list contains heterogeneous elements. Moreover, Python arrays are implemented in C which makes it a lot faster than lists that are built-in in Python itself.
Two reasons, why the List might be slightly slower: To look up a element in the list, a method of List is called, which does the look up in the underlying array. So you need an additional method call there. On the other hand the compiler might recognize this and optimize the "unnecessary" call away.
As my test code:
$value = 'dfkjgnnfdjgnjnfdkgn dnf gnjknkxvjn jkngjsrgn';
$value1 = 'dfkjgnnfdjgnjnfdkgn dnf gnjknkxvjn jkngjsrgn';
$start = microtime(true);
for ($i = 0; $i < 1000000; $i++)
$value = preg_replace( array('/_{1,}/', '/-{2,}/'), array('_', '-'), $value);
echo microtime(true) - $start.'<br>';
$start1 = microtime(true);
for ($i = 0; $i < 1000000; $i++){
$value1 = preg_replace('/_{1,}/', '_', $value1);
$value1 = preg_replace('/-{2,}/', '-', $value1);
}
echo microtime(true) - $start1;
1.4254899024963
1.2811040878296
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With