Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using an array faster than having multiple statements?

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.

like image 857
insertusernamehere Avatar asked Aug 08 '12 11:08

insertusernamehere


People also ask

Are arrays faster than lists?

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.

Which is more efficient array or list?

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.

Why are arrays more efficient than lists?

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.

Why are lists slower than arrays?

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.


1 Answers

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

like image 145
Leri Avatar answered Sep 21 '22 14:09

Leri