php – is isset way is faster than array_search?

Theory speaking, looking into hashmap (isset) is faster than array_search or in_array.

But, let’s see how it work in php in practice.

Look at this code block:

Given a keyword in a language, then the function return the gender code (1: men, 2: women).

Make thing done with above code, yeah! But can we optimize it a bit: faster, and easier to read??

Why not? So, take a look at this block of code:

It takes O(n*logn) for time complexity!

if we change the data structure of it a bit like this

$genderKeywords array now acts as a hashmap[1]. Which O(1) for looking the key in it. Finally, check it out

It’s O(1) for time complexity, and easier to read, isn’t it ??

Testing performance:

optimize way

normal way

Well, the optimize way in theory is not faster than the normal way in practice :D. So, at this point, we can’t see much improvement here, but at least the code of new implementation (hashmap way) is cleaner.

So, theory isn’t always perform well in practice! is it?