Comparing the efficiency of using arrays versus mapping to an object and accessing data in JavaScript

When considering the basics of computer science, it is understood that searching an unsorted list typically occurs in O(n) time, while direct access to an element in an array happens in O(1) time for HashMaps.

So, which approach yields better performance: mapping an array to a dictionary and accessing elements directly, or simply using includes()? This question pertains specifically to JavaScript, as the answer likely hinges on how includes() and {} are implemented at their core.

let y = [1,2,3,4,5]
y.includes(3)

or...

let y = {
          1: true,
          2: true
          3: true
          4: true
          5: true
        }
5 in y

Answer №1

It is indeed true that object lookup operates in constant time - O(1) - making the use of object properties instead of an array a viable option. However, when you simply need to determine if a value exists within a collection, employing a Set would be more suitable. A Set is a generally unordered group of values that can also be searched in linear time. Opting for a plain object would necessitate having values alongside keys, which may not be relevant. Therefore, opting for a Set is recommended.

const set = new Set(['foo', 'bar']);
console.log(set.has('foo'));
console.log(set.has('baz'));

This approach proves beneficial when multiple values need to be checked within the same Set. Nevertheless, adding elements to the Set (similar to adding properties to an object) entails an operation of O(N). Hence, if you only require a single value lookup once, there is no advantage to utilizing either this method or the object technique. In such scenarios, resorting to using an array and the includes method would suffice.

Answer №2

Updated 04/29/2020

The recent analysis pointed out that V8 may be optimizing the array includes calls. In order to achieve more expected results, it is suggested to assign to a variable and use it. The updated version shows Object address as the fastest, followed by Set has, with Array includes trailing in performance (based on my system/browser).

While I still maintain my original point about testing assumptions when making micro-optimizations, it is important to ensure the validity of your tests ;)

Original

Despite the common expectation that Object address and Set has would have better performance than Array includes, benchmarks against Chrome show otherwise.

In my tests with Chrome, Array includes significantly outperformed the other methods.

Local testing with Node yielded more anticipated results where Object address performed the best, Set has came close behind, and Array includes was slightly slower than both.

The key takeaway here is that if you are considering micro-optimizations, it is advisable to benchmark instead of assuming what might work best for your specific scenario. Ultimately, implementation plays a crucial role, as indicated by your question. Therefore, optimizing for the target platform is essential.

Here are the results obtained:

Node (12.6.0):

ops for Object address 7804199
ops for Array includes 5200197
ops for Set has 7178483

Chrome (75.0):

https://i.sstatic.net/PRLv6.png

Answer №3

Although not a direct answer to the query, I conducted a related performance test using my Chrome dev tools.

function getRandomInt(max) {
    return Math.floor(Math.random() * max);
}
var arr = [1,2,3];
var t = performance.now();
for (var i = 0; i < 100000; i++) {
    var x = arr.includes(getRandomInt(3));
}
console.log(performance.now() - t);
var t = performance.now();
for (var i = 0; i < 100000; i++) {
    var n = getRandomInt(3);
    var x = n == 1 || n == 2 || n == 3;
}
console.log(performance.now() - t);
VM44:9 9.100000001490116
VM44:16 5.699999995529652

The array includes syntax appealed to me aesthetically, prompting me to assess its impact on performance when used to check if a variable matches one of several enums. Surprisingly, with a short list, like [1,2,3], there seems to be minimal impact on performance. To verify this, I ran another test.

function getRandomInt(max) {
    return Math.floor(Math.random() * max);
}
var t = performance.now();
for (var i = 0; i < 100000; i++) {
    var x = [1,2,3].includes(getRandomInt(3));
}
console.log(performance.now() - t);

var t = performance.now();
for (var i = 0; i < 100000; i++) {
    var n = getRandomInt(3);
    var x = n == 1 || n == 2 || n == 3;
}
console.log(performance.now() - t);
VM83:8 12.600000001490116
VM83:15 4.399999998509884

Interestingly, I found that the method I preferred and actually utilized had a significant impact on performance compared to the initial test, especially when executed multiple times. Therefore, incorporating it within an Array.filter in scenarios like a React Redux selector might not be advisable as initially intended.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to successfully set up a React application without encountering any installation errors

Hey everyone, I've been trying to install React on my system for the past two days but keep encountering errors. Initially, I used the commands below to install the React app and it worked smoothly: 1. npm install -g create-react-app 2. create-react- ...

Click on the link to see the jQuery effect in action

I'm trying to achieve a fade-out effect on the current page followed by fading in a new one. The fade-in effect is working fine, but when I click on the link, the new page loads without first fading out the existing content. The div that I want to app ...

What could be causing the code to not wait for the listener to finish its execution?

I've been attempting to make sure that the listener has processed all messages before proceeding with console.log("Done") using await, but it doesn't seem to be working. What could I possibly be overlooking? const f = async (leftPaneRow ...

What are the steps to transform an object containing arrays into strings and then embed them into my HTML code?

Here is the code I need to add to my errors array and send the values to my HTML client-side template: { "email": [ "user with this email already exists." ] } I am looking for something like this: "user with t ...

PHP struggles to parse a JSON array

While attempting to parse the response from a service request, I encountered an issue where using json_decode did not work as expected. Specifically, I need to determine if ["body"]->enquiry->status is equal to “OPEN”. Can someone provide guid ...

What is the best way to ensure that the buttons remain in place once they have been clicked to reveal a drop-down menu?

Is there a way to keep 3 buttons inline and prevent them from moving when clicked to open a submenu? Changing their positions results in them stacking on top of each other. Any help or suggestions would be greatly appreciated, thank you! Here is the code ...

Is there a way to efficiently update specific child components when receiving data from websockets, without having to update each child individually?

Currently, my frontend requires updated data every 2 seconds. The process involves the frontend sending an init message to the backend over a websocket. Upon receiving this message, the backend initiates an interval to send the required data every 2 second ...

Localhost file not refreshing

I'm feeling quite frustrated at the moment. It seems like such a simple issue, but I can't seem to figure it out. I have created a basic webpage with a "tree-view" structure. In my readjson.js file, I am reading from a json file located in json/ ...

What is the process for combining three 2D arrays and showcasing the outcome as an image?

I am currently working with three 2D arrays that contain red, green, and blue pixel values of an image. The original image is blurred and then divided into these RGB arrays so that I can apply a function to each array in order to deblur the images. After t ...

Incorporating AngularJS and Bootstrap for seamless pagination experience

My JSON data looks like this: http://localhost:3001/images?page=1 {"images":[{"_id":"542e57a709d2d60000c93953","name":"image1","url":"http://www.syll.com","__v":0},{"_id":"542e58e19d237e5b790f4db2","name":"image154","url":"www.rufyge.com"},{"_id" ...

strange occurrences while handling double pointer variables

I'm perplexed by the fact that I am unable to manipulate pointers correctly in this small program: #include <stdio.h> #include <stdlib.h> #include <string.h> void change(char *s[][15]){ int i=0; ...

Troubleshooting node modules for browser compatibility

Looking for assistance with running a specific node module in a browser. The module in question is called fury.js. I attempted to use browserify, however, encountered an error stating "ReferenceError: fury is not defined" when trying to utilize it. In th ...

generate a list based on the data inside an array of objects

How can I extract the values from the 'urban' field of type 'gasolina'? { ... "fuelUse" : { "urban" : [ { "value" : 6.2, "unit" : "km/l&qu ...

Setting up a connection between an Express server and a Mongoose database in

As someone who is relatively new to the express framework and mongoose database, I have mainly worked with relational databases in the past. I am attempting to create a database using the script below. Currently, mongod.exe is running and listening on loca ...

What is the best way to display a loading image and temporarily disable a button for 3 seconds before initiating the process of sending post data from another page via

Is there a way to display a loading image and disable a button for 3 seconds before sending post data from another page using AJAX POST? Once the OK button is clicked, I would like the loading image to appear and the <input type="button" value="Check" ...

The `toString` function is displaying an array instead of the expected string

As a beginner in programming, I am currently enrolled in an introductory JavaScript course. However, I am facing an issue with my assignment where the toString method is printing an array instead of a string. Despite thorough research, I have been unsucces ...

When the button is clicked, the image vanishes into thin

One common issue is the image disappearing when users click on the Rotate Anti-clockwise or Rotate Clockwise buttons. This can be a frustrating problem to tackle! Check out this link for more information. If you run into this issue, here are some tips: ...

display the values of the array object within the ajax success callback

When I receive the result, it looks like this https://i.sstatic.net/q4iUb.png But now I want to display that content inside a dropdown box with option values. How can we accomplish that? My current approach is as follows: var data = data.user_contacts ...

Determination of Array Size using Powershell

Having some trouble error trapping an empty array in the code below. Any suggestions on how to correct the syntax? $inputstring = "MyOtherFile.rdl" "MyFile.rdl" $cleanstring = $inputstring.replace(""" """,";") $filearray = $inputstring.split(";") if ( ...

Techniques for transferring JavaScript variables within a URL using AJAX

Is there a correct way to pass the values of accesstoken and pageid inside the URL I am using? Any ideas on how to do it properly? <script type="text/javascript"> function makeUrl() { var accesstoken = "12345679|bababashahahhahauauuaua"; ...