473,385 Members | 2,029 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,385 developers and data experts.

Optimize Loops to Compare Two Arrays

gits
5,390 Expert Mod 4TB
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 38136

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

Similar topics

18
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...
2
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...
3
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...
1
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
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...
2
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...
1
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...
5
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. ...
9
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}, ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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...

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.