'How can we improve this code for better performance
This question was asked to me in an interview. But I couldn't think of a way to improve it. can you improve this?
$target = array(1,rand(1,5));
for ($i = 0; $i < 10; $i++) {
$target = array_merge( $target, array(rand($i,5),rand(1,$i)) );
}
Solution 1:[1]
array_merge has performance overhead,
So simply use
<?php
$target = array(1,rand(1,5));
for ($i = 0; $i < 10; $i++) {
$target[]=rand($i,5);
$target[]=rand(1,$i);
}
You may add var_dump($target); to the end of the script (and to your original script) to see the result.
Original Code: https://sandbox.onlinephpfunctions.com/c/96b0c
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
