473,609 Members | 1,871 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Optimize Loops to Compare Two Arrays

gits
5,390 Recognized Expert Moderator Expert
This little article will show you how to optimize runtime performance when you need to compare two arrays (a quite common task). Have a close look at the entire article, and you will see the advantage of the final code snippet :)

Let's assume we want to find out the element that is contained by both of the lists.

Expand|Select|Wrap|Line Numbers
  1. var list1 = [1, 2, 3, 4, 5, 6];
  2. var list2 = ['a', 'b', 'c', 3, 'd', 'e'];
  3.  
  4. for (var i in list1) {
  5.     for (var j in list2) {
  6.         if (list1[i] == list2[j]) {
  7.             alert('found ' + list1[i] + ' in both lists');
  8.         }
  9.     }
  10. }
  11.  
It's a good idea to break out of the entire loop when the inner condition returns true, so you will get even faster execution if you do the following:

Expand|Select|Wrap|Line Numbers
  1. var list1 = [1, 2, 3, 4, 5, 6];
  2. var list2 = ['a', 'b', 'c', 3, 'd', 'e'];
  3.  
  4. outerloop: for (var i in list1) {
  5.     for (var j in list2) {
  6.         if (list1[i] == list2[j]) {
  7.             alert('found ' + list1[i] + ' in both lists');
  8.             break outerloop;
  9.         }
  10.     }
  11. }
  12.  
But have in mind that this is not the best way to compare two arrays!

By using two loops, you have up to n*m steps to perform. But we can do better than that! How about n+m, hmm? ;)

Have a look at the following implementation:

Expand|Select|Wrap|Line Numbers
  1. var list1 = [1, 2, 3, 4, 5, 6];
  2. var list2 = ['a', 'b', 'c', 3, 'd', 'e'];
  3. var lookup = {};
  4.  
  5. for (var j in list2) {
  6.     lookup[list2[j]] = list2[j];
  7. }
  8.  
  9. for (var i in list1) {
  10.     if (typeof lookup[list1[i]] != 'undefined') {
  11.         alert('found ' + list1[i] + ' in both lists');
  12.         break;
  13.     } 
  14. }
  15.  
Since it is much faster to search for an element in an array by its key rather than its value, we create an index array, 'lookup', and copy all of the values from list2 as keys in lookup. When this code executes, lookup looks like this:

Expand|Select|Wrap|Line Numbers
  1. var lookup = {
  2.     'a': 'a',
  3.     'b': 'b',
  4.     'c': 'c',
  5.     '3': '3',
  6.     'd': 'd',
  7.     'e': 'e'
  8. };
  9.  
Now it becomes a simple matter of running through list1 and checking to see if there is a matching index in lookup, which is MUCH faster than looping through list2!

Good luck and kind regards.
Aug 27 '07 #1
0 38195

Sign in to post your reply or Sign up for a free account.

Similar topics

18
39986
by: Mike Bartels | last post by:
Hi Everyone! I have two Arrays A and B. Both arrays are byte arrays with 7 bytes each. The contents of array A and B are the same A = {1, 2, 3, 4, 5, 6, 7}; B = {1, 2, 3, 4, 5, 6, 7}; When I do
2
16349
by: nobs | last post by:
Hi I have two byte arrays (each with a length of 8 bytes) an I'd like to compare them if they are equal. The operator == shouldn't work because its not a basic Data Type so I used the method Equal, but it also isn't working. right know I use if(mykey.Length!= keytocheck.Length)
3
21314
by: Lance | last post by:
What is the fastest way to determine if two arrays that contain ValueTypes are equal? For example, lets say I have the following: Dim pt1 as New Drawing.Point(1, 2) Dim pt2 as New Drawing.Point(2, 3) Dim pt3 as New Drawing.Point(3, 4) Dim pt4 as New Drawing.Point(4, 5) Dim A() as Drawing.Point = {pt1, pt2, pt3}
1
2024
by: Jacob Thastrup | last post by:
Hi is there an easy way to compare arrays without going through each entry in the arrays? Say I have two arrays and I want to find entries that are not present in both. Thanks Jacob Thastrup
8
3393
by: Turbot | last post by:
Hello, Anyone know how to compare two byte arrays without going through each item in the array. I actually want to compare two bitmap objects to see if they both contain the same picture bit have been unable to do this. I figured if I converted them to byte arrays there would be a simple way of comparing them but I have had no luck. Thanks in advance.
2
4097
by: Florian G. Pflug | last post by:
Hi Since sometime yesterday, my postgresql (7.4.5) reports "ERROR: cannot compare arrays of different element types", when I analyze a specific table in my database. Here is the tables definition: Column | Type | Modifiers -------------------+------------------------+---------------------------------------------------- self | datagraph."GOLink" | not null default
1
1782
by: naqqash | last post by:
HI I am a beginner i VB please someone tell me how to compare values in array for exmple i've created an array for 10 day temperature now i want to know the maximum and minimum temperature in these 10 days what will be the way plzzzzzzzzzzzzzz help!!!!
5
2809
blyxx86
by: blyxx86 | last post by:
Happy Christmas Eve everyone, I've been looking around for the past few hours and my searches return useful information, but not with the same effect in mind as what I am trying to achieve. Essentially I am trying to create some form that is pulled from a MySQL database using two queries that I pull into their result sets and then close the connection and then display information in the first query on the top, and then the related...
9
24567
by: capablanca | last post by:
How can I compare arrays to see if they are equal, they have the same amount of elements for example: array = {{2,4,5,7,8},{1,3,5,7,8},{3,4,5,7,8}, {4,6,7,8,9},{2,4,5,7,8}};
0
8076
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8573
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8541
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8406
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6057
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5510
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4021
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2531
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1389
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.