How to improve your Array search using Javascript

How to improve your Array search using Javascript

In JavaScript, day-to-day tasks often involve numerous queries that sometimes require operations with arrays. In this post, I'll focus on one of the most common tasks: queries.

Let's say we have an array with 50,000 users and an array of 200,000 posts, each related to its author through a createdBy field

In this example, we want to retrieve information about the posts with their associated authors (as we would receive from a database query with relations). To achieve this, we could use the following code using .find().

This code segment would provide us with the information as we intend it, but processing this information takes an average of 3.158 seconds to execute. This time is too high and can be optimized. To do this, we'll index the users to make accessing this information much faster.

The .reduce() function will allow us to easily create this index by executing a reducing function on each element of the array and returning a single value. In this case, it will assign a field (our indexed value) and assign the user object as its value.

This means that if we have a user

it will be stored in the object with its id as the key:

Once this is done, we can query the array as follows:

Using indexing, the search process using the same data takes 20.881 milliseconds, an improvement of 99.09% compared to the time using .find().

This process can also be used when comparing multiple fields using composite keys, indexes composed of several fields. In our example, we want to index those users who have the role of developers:

Using the method with .find:

Using the indexed method:

In this case, the method with .find takes 4.682 seconds while the indexed method takes 94.999 milliseconds, resulting in an improvement of 97.97% in execution time.

The code for this tests is available at: https://gist.github.com/alex55132/c7f6b20289db6ae0587eb108329efc90

要查看或添加评论,请登录

Alejandro Urdiales del Pino的更多文章

  • Introduction to Domain Driven Design (DDD)

    Introduction to Domain Driven Design (DDD)

    Domain-Driven Design (DDD) is a software development philosophy first introduced by Eric Evans (“Domain-Driven Design:…

社区洞察

其他会员也浏览了