6

I have a question that I cannot find an answer.

I'm constructing a very big array that contain hex values of a file (like $array[0]=B5 $array[1]=82 and so on until $array[1230009])

When I create a function to manipulate some offsets in that array and pass the $array as reference ( function parse(&$array) { ... }) it takes WAY longer than if I pass the array normaly ( function parse($array) { ... }) ..

How is that possible ?

PS: Is there any faster way not to use array at all ? Just to use a $string = "B5 82 00 1E ..etc", but I need to track the Offset as i advance in reading hex values as some of this values contains lengths"

pufos
  • 2,890
  • 8
  • 34
  • 38
  • 1
    It takes longer to pass the array, or it takes longer to perform your function on the array that you pass? Also, this is not a RAM efficient means of referencing each byte of a file. You should use strings instead methinks. – crush Feb 14 '12 at 21:16
  • possible duplicate of [In PHP (>= 5.0), is passing by reference faster?](http://stackoverflow.com/questions/178328/in-php-5-0-is-passing-by-reference-faster) – PeeHaa Feb 14 '12 at 21:17
  • it takes like 30 seconds to perform the function on the array (by reference) and 2 second to perform the function on the array by normal passing – pufos Feb 14 '12 at 21:18

1 Answers1

3

There are some informations that might help in the following article : Do not use PHP references

Close to the end of that post, Johannes posts the following portion of code (quoting) :

function foo(&$data) {
    for ($i = 0; $i < strlen($data); $i++) {
        do_something($data{$i});
    }
}

$string = "... looooong string with lots of data .....";
foo(string);

And a part of the comment that goes with it is (still quoting) :

But now in this case the developer tried to be smart and save time by passing a reference.
But well, strlen() expects a copy.
copy-on-write can't be done on references so $data will be copied for calling strlen(), strlen() will do an absolutely simple operation - in fact strlen() is one of the most trivial functions in PHP - and the copy will be destroyed immediately.

You might well be in a situation like this one, considering the question you are asking...

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • EDITED: Ok I understand that now but : How to use strings like $string = "B5 82 00 1E .... etc" ? But I need to perform a login on every hex value and need to keep the offset as I advance in reading it – pufos Feb 14 '12 at 21:22