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"

3
  • 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. Commented Feb 14, 2012 at 21:16
  • possible duplicate of In PHP (>= 5.0), is passing by reference faster? Commented Feb 14, 2012 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 Commented Feb 14, 2012 at 21:18

1 Answer 1

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...

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.