For example, suppose I have 2 arrays:

let arr1=[5,2,1];
let arr2=["abcde","ab","a"];

my work is simple : to check if length of strings in arr2 are larger than corresponding element with same index in arr1, so:

let arr1=[5,2,1];
let arr2=["abcde","ab","a"];

is true,


let arr1=[5,3,1];
let arr2=["abcde","ab","a"];

is false,


let arr1=[5,2,1,1];
let arr2=["abcde","ab","a"];

is also false. I'm struggling where I should put the checking of array length:

Style 1: put it outside for loop:

function isAllLarger(arr1,arr2){
  if(arr1.length>arr2.length){
    return false;
  }
  for(let i=0;i<arr1.length;i++){
    if(arr2[i].length<arr1[i]){
      return false;
    }
  }
  return true;
}

Style 2 : put it inside for loop:

function isAllLarger(arr1,arr2){
  for(let i=0;i<arr1.length;i++){
    if(i>=arr2.length|| arr2[i].length<arr1[i]){
      return false;
    }
  }
  return true;
}

Which one should I use?

有帮助吗?

解决方案

Both are perfectly possible. But there are reasons why you should prefer option 1:

  • First, option 1 clarifies the intent: you immediately grasp the special case and understand how to handle it. With the second option an uninformed reader (or your future you?) would have to deduct from the code that there is a special case. Of course, it's feasible but not as easy as with the first option.
  • Second, option 2 requires one more condition evaluation at each iteration. But let's be honest: this argument is not the main reason, just an intellectual curiosity. The additional execution time would be marginal, and an optimizing compiler could even get rid of it.
  • Finally (thanks to John Wu for drawing attention on this), option 2 would unnecessarily process elements in the loop: we could already know the final result due to the different of length.

其他提示

In my opinion, solution 1 is better than solution 2. The simple reason for that is the overall performance. Any code which reduces the number of iteration is good for any application. Solution 1 does the same as if condition returns false then it will reduce the number of iterations.

许可以下: CC-BY-SA归因
scroll top