FacebookTwitterGoogle+Share

When paths diverge indecision attacks with a sort of brutal pride

Guys, I have a problem. Sometimes a decision seems so trivial it stops me completely, and that was the case today.

I was trying to decide how to pass data:

data[0] = 3
data[1] = 9

or

data[3] = 1
data[9] = 1

The first method creates an array whose elements are the object IDs we want. The second, an associative array whose keys are our IDs.

I know. You’re thinking: Who the eff cares? Also, I know that you’re Shaun.

And you’re right, it doesn’t matter. At all. But I had no preference in terms on convention.

I did what anyone would do — the only thing I could do, I wrote a script to test the speeds of the two pertinent PHP functions. I call it in_array vs. array_key_exists. In case you haven’t guessed, it compares the relative speeds of in_array and array_key_exists.

Feel free to play with it.

In fact, I’ll post the code. Give it a look, and decide I did it wrong.

But who really wants to click on so many links?

Good news! You don’t even have to; array_key_exists won. And for the search engines: array_key_exists is faster than in_array.

If you didn’t take my word for it, and jumped from link to link searching for personal verification, you may have noticed that decreasing the number of operations often leads in_array to victory. This, I suspect, is because with fewer operations unrelated overhead has greater impact.

Guys, this is important stuff. Those ~0.003 seconds over 20,000 operations is a big deal. In fact, I submit it is everything. Those are three one thousandths of a second you might otherwise never get back.

 

Comments

  1. Shaun says:

    I wouldn’t say who the eff cares, there are many situations where .003 seconds over 20000 operations matters. You probably weren’t in one of them though. 😛

    Also I will be on Xbox Live at 7.

You must be logged in to post a comment.