I am trying to understand better what causes a branch prediction to be calculated, and what does not.
Say for example I have an array which contains 1's and 0's. I want to loop through this array, and if it reads a 0 do something, but if it reads 1 do something else.
Using JavaScript it would look like this:
var array = [0, 1, 1, 1, 0, 0, 0];
for(i=0; i < array.length; i++){
if(array[i] == 0){
// Do The 0 Instruction
}else{
// Do The 1 Instruction
}
}
I know that this will cause branch predictions to be made because the program won't know what steps it needs to take until it has read the data from the array.
However what if I pre-processed the array to combine the number of consecutive 1's or 0's into a single number. So for example the array would change to this:
var array = [0, 1, 1, 1, 0, 0, 0];
var condensedArray = [1, 3, 3];
Now instead of using if statements to branch my instructions, I can use loops like this:
var condensedArray = [1, 3, 3];
for(i=0; i < condensedArray.length; i+=2){
for(j=0; j < condensedArray[i]; j++)
//Do The 0 Instruction
for(j=0; j < condensedArray[i+1]; j++)
//Do The 1 Instruction
}
Does this still cause branch predictions to be calculated and missed? And if so is it at least more efficient that using an if statement to test every index of the original array?
Edit: In the comments I was asked how would I know if the array starts with a 0 or a 1? I left that out for simplicity and don't want to edit the code above to make it any longer, but I would have a single if statement at the start of the program that says if the array begins with 0 or 1. Then that single branch would put the loops in the correct order.