我想知道哪种代码效率更高,我有两个选择。你会说哪个更有效率,为什么?谢谢。
选项A
array1 size is 1000
array2 size is 2000
for(int i = 0; i < array1.size(); i++)
{
for(int j = 0; j < array2.size(); j++) {
if(array1[i].method() == array2[j].method()) // CHECKS IF THERE'S AN EQUAL IN BOTH ARRAYS
{
doSomething();
break;
}
if(j == array2.size()-1) // CHECKS IF ARRAY1 DID NOT FIND A MATCH
{
doSomething();
break;
}
for(k = 0; k < array1.size(); k++)
{
if(array1[k].method() == array2[j].method()) // CHECKS IF THERE'S AN EQUAL IN BOTH ARRAYS
{
// BUT DOES NOTHING BECAUSE IT WAS DONE ALREADY UPSIDE
break;
}
if(k == array1.size()-1) // CHECKS IF ARRAY2 DID NOT FIND A MATCH
{
doSomething();
break;
}
}
}
}
选项B
array1 size is 1000
array2 size is 2000
for(int i = 0; i < array1.size(); i++)
{
for(int j = 0; j < array2.size(); j++) {
if(array1[i].method() == array2[j].method()) // CHECKS IF THERE'S AN EQUAL IN BOTH ARRAYS
{
doSomething();
break;
}
if(j == array2.size-1) // CHECKS IF ARRAY1 HAS NO ARRAY2 MATCH
{
doSomething();
break;
}
}
}
for(int j = 0; j < array2.size(); j++)
{
for(int i = 0; i < array1.size(); i++) {
if(array2[j].method() == array1[i].method()) // CHECKS IF THERE'S AN EQUAL IN BOTH ARRAYS
{
// BUT DOES NOTHING BECAUSE IT WAS DONE ALREADY UPSIDE
break;
}
if(i == array1.size-1) // CHECKS IF ARRAY2 HAS NO ARRAY1 MATCH
{
doSomething();
break;
}
}
}
我目前已经实施了选项 B,我想知道我是否应该转向选项 A,因为尽管选项 A 可能需要更多时间,但我不知道是执行两个循环还是执行所有迭代需要更多时间。或者也许是一样的,我真的不知道。
狐的传说
哆啦的时光机
holdtom
相关分类