Home > Software engineering >  How can we improve this code for better performance
How can we improve this code for better performance

Time:05-01

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)) ); 
} 

CodePudding user response:

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

My answer: https://sandbox.onlinephpfunctions.com/c/fc2a8

  •  Tags:  
  • php
  • Related