Indexing PHP

By sorting the data, you spend time up front, betting it will pay off when you need to search. But even this searching costs something. A binary search may take several steps. When you need to do hundreds of searches, you may look for further improvement in performance. One way is to perform every possible search beforehand, creating an index. A lot of work is done at first, which allows searches to be performed fast.

Let's explore how we can transform the binary search into a single lookup. We want an array that, given a name, returns its position in the

A Binary Search

A Binary Search

original array. Our list of employees has two people with the same name, so we'll have to build a list of matches. We won't bother sorting the list. It won't help, because we will be visiting every element of the array. As we visit each element, we create a new array. The index of this array is the name of the employee. Each element of the index will be an array of indices in the employee array. Once the index is created, finding an employee is a single statement. If the name is found in the array, we can retrieve the index values for the employee array.

This example is not very realistic because we're only making one search, and we're building the index with each request. The index needs to be built only once, as long as the employee array doesn't change. You could save the array to a file, perhaps using PHP serialization functionality, and then load it when needed. I wrote similar code for the FreeTrade project that indexes keywords that appear in pages of a Web site.

Indexing

Indexing

Indexing

Of course, databases present a larger solution to managing data. In most cases, it's best to rely on a database to store large amounts of data, because databases have specialized code for searching and sorting.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP Topics