U
U
Urukhayy2015-05-10 12:46:28
Programming
Urukhayy, 2015-05-10 12:46:28

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

3 answer(s)
S
Sergey, 2015-05-10
@Urukhayy

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;
}

jsperf.com/loop-unroll-simple
This example already shows that the unroll works, although the performance gain is not that big. The JS optimizing compiler can do it there too.
In your case, you have conditions that already cause restrictions on how much you can parallelize (in fact, nothing can be parallelized at all under conditions), so there will be no profit due to the unrolling of the cycle.

O
olexandr7, 2015-05-10
@olexandr7

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

M
Mrrl, 2015-05-10
@Mrl

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 question

Ask a Question

731 491 924 answers to any question