Exploring the intricacies of what triggers a branch prediction to be computed and when it doesn't come into play is my current goal.
Let's consider a scenario where I have an array consisting of 1's and 0's. My objective is to iterate through this array, performing one action if it encounters a 0, and another action in case of a 1.
If we were to implement this logic in JavaScript, it would appear as follows:
var array = [0, 1, 1, 1, 0, 0, 0];
for(i=0; i < array.length; i++){
if(array[i] == 0){
// Perform Operation for 0
}else{
// Perform Operation for 1
}
}
I am aware that such a setup leads to branch predictions being made because the program can't anticipate the necessary steps until it processes the array data.
Now, let's consider a different approach where we preprocess the array by grouping consecutive 1's or 0's into a single number. This results in transforming the array like so:
var array = [0, 1, 1, 1, 0, 0, 0];
var condensedArray = [1, 3, 3];
By avoiding conditional statements to direct instructions, we can use loops instead, as demonstrated below:
var condensedArray = [1, 3, 3];
for(i=0; i < condensedArray.length; i+=2){
for(j=0; j < condensedArray[i]; j++)
// Perform Operation for 0
for(j=0; j < condensedArray[i+1]; j++)
// Perform Operation for 1
}
This raises the question: Does this new method still lead to the computation and potential misses of branch predictions? And even if it does, is it more efficient than using if statements to check every index of the original array?
Edit: Some may wonder about determining whether the array starts with 0 or 1. For simplicity, I omitted this detail in the above code snippet, but in a real scenario, a single initial if statement can handle this by organizing the loops accordingly based on the starting value of the array.