Answer the question
In order to leave comments, you need to log in
Looping through an array or checking values with a check?
What will be faster and more optimal?
for(new i; i != 100; i++)
{
if(Array[i] == variable) break;
}
vs
if(1232 == variable || 2232 == variable ||
1532 == variable || 1432 == variable ||
1262 == variable || 12332 == variable || ...) // и так множество значений, которые даны в массиве Array
Answer the question
In order to leave comments, you need to log in
In terms of performance - no difference, since the second option is equivalent to a loop. But you understand that the first option is better. If you are worried about performance - then binary search. But by no means the hell that you brought. The fastest way to search is by a hash map, since the complexity of the selection is always O (1).
In general, for most languages, including interpreted ones, loop unrolling gives a performance boost. What is causing the acceleration? And due to the fact that all these instructions inside the loop are independent of each other, we do not have write conflicts (and cannot be) and therefore the processor calmly parallels the execution of instructions. This is convenient when you need to calculate some long array (for example, add brightness to a picture).
Example. Let's take an array of 1,000,000 numbers, and try to make a copy of it, with the value doubled:
var data = range(1000000);
var result = range(1000000);
// обычный вариант
for(var i = 0;i<1000000;i++) {
result[i] = data[i] * 2;
}
// развертка цикла
for(var i = 0;i<1000000;i+=4) {
result[i] = data[i] * 2;
result[i+1] = data[i+1] * 2;
result[i+2] = data[i+2] * 2;
result[i+3] = data[i+3] * 2;
}
I think that it would be better to loop through all the elements until it is found, and not to fence the horror that is below
In C++, direct checking is about twice as fast as loop checking. I checked for an array of 10 elements (checked if the number is in the first 10 primes). The problem with the loop is that it is difficult to write an else part for such an "if" - you either need to add an extra boolean variable or use goto.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question