Using Links in PHP

I ask this question because I found out that in programming and development you must have a good reason for making decisions. I am a php student and I am at the crossroads here, I use simple increment to try to get what I ask. I'm certainly not here to start a discussion about the pros and cons of links, but when it comes to php, which is the best programming practice:

function increment(&$param) {
      ++$param;
}

against.

function increment($param){
 return ++$param;
}

$param = increment($param);
+3
source share
8 answers

First, links are not pointers .

, @John , . , microtime() . , . float microtime(true).

, :

<?php

$param = 1;

$start = microtime(true);

for($i = 1; $i <= 1000000; $i++) {
    $param++;
}

$end = microtime(true);

echo "increment: " . ($end - $start) . "\n";

, Macbook 2.4GHz PHP 5.3.2.

  • : 2,14
  • : 2,26
  • , : 0,42 .

, , 5,3%, 81% - .

, , . , , , .

, , - , .

, . , , :

  • , . , , , ( ", ?", - ?)
  • . , , , . foreach .
+10

. , . , return.

, , array_push:

int array_push(array &$array, mixed $var[, mixed $...])

- . , , , .

array_push($array, 42); // most likely use case

// if you really need both versions, just do:
$old = $array;
array_push($array, 42);

array_push , :

// array_push($array, $var[, $...])
$array = array_push($array, 42); // quite a waste to do this every time

, pow :

number pow(number $base, number $exp)

, , . , pow .

$x = 123;
$y = pow($x, 42); // most likely use case

pow , :

// pow(&$base, $exp)
$x = 123;
$y = $x; // nuisance
pow($y, 42);
+3

, , .

$param++;

- , .

+2

:

function increment($param){
 return $param++;
}

$param = increment($param);

. increment() $param. , ++ $param $param + 1;

, , , , (, PHP- ).

+2

, ( , PHP) . , 1 ; , .

, , (PHP ) $param - .

+1

:

<?php

function increment(&$param){
 $param++;
}
$param = 1;

$start = microtime();

for($i = 1; $i <= 1000000; $i++) {
    increment($param);
}

$end = microtime();

echo $end - $start;

?>

, 0,42 0,43, , .55 .59

<?php

function increment($param){
 return $param++;
}
$param = 1;

$start = microtime();

for($i = 1; $i <= 1000000; $i++) {
    $param = increment($param);
}

$end = microtime();

echo $end - $start;

?>

, , , .

+1

, .

, , , , int, ( , PHP5).

0

I would say that it will greatly depend on what you are doing. If you are trying to interact with a large data set without requiring an additional copy of it in memory - continue, go by value (your second example). If you want to save memory and interact directly with the object - pass by reference (your first example)

0
source

Source: https://habr.com/ru/post/1748260/


All Articles