0

My question is this. Assume I have an array called A and I only want certain operations to happen depending on a condition. What is more efficient:

I)

A.forEach(x => { 
  if (condition1) {
    //do stuff1
  } 
  else if (condition2) {
    //do stuff2
  }
  else if (condition3) {
    //do stuff3
  } 
});

or

II)

if (condition1) {
  A.forEach(x => {
    //do stuff1}
  )}
}
else if (condition2) {
  A.forEach(x => {
    //do stuff2}
  )}
}
else if (condition3) {
  A.forEach(x => {
    //do stuff3}
  )}
}

or is there a much better way to do what I'm after? Thanks!

MikamiHero
  • 299
  • 2
  • 6
  • I don't see how I is the same as II? II will run many many times for each. I will only foreach once. – jdmdevdotnet Mar 02 '18 at 03:16
  • i also have a question for you , does the condition affect the entire array or just applies to every index of the array ?, for the former use your second method, for the later use your first method – 0.sh Mar 02 '18 at 03:16
  • It applies to a few elements of the array, so I guess I will opt for the second method :-) – MikamiHero Mar 02 '18 at 03:23
  • I'm voting for I. Or II. Or... I dunno, depends on the weather I guess – connexo Mar 02 '18 at 03:33
  • You need the condition checking on each iteration over the array element, that is, **do these conditions involve x**? If not, II is clearly superiour. – connexo Mar 02 '18 at 03:35
  • connexo - how is the weather then? :-p but in all seriousness, thanks for your comment. Helped out! – MikamiHero Mar 02 '18 at 03:40

2 Answers2

1

Testing the condition first, then call the relevant forEach. Assuming, of course, that the conditions are unrelated to the specific index within A. If the condition truthiness depends on the index, then you have to evaluate the conditions within the forEach

i.e. the answer depends on what constitutes conditionN

tehhowch
  • 9,645
  • 4
  • 24
  • 42
1

Based on the info provided there's no telling if there's a more efficient algorithm.

Your second option only checks conditions 1, 2, and 3 one time, but option one checks them all n times. Option II looks like more code but it is faster.

JasonB
  • 6,243
  • 2
  • 17
  • 27