Member-only story
Perform Vector Calculations Fast Using Java’s new Vector API (Incubator Mode)
Let us say you want to add the elements of two arrays which are of equal size.
The first element of array 1 should be added to the first element of array 2,
The second element of array 1 to the second element of array 2 and so on until you reach the end of the arrays.
How do you do this in Java?
Using a code like this :
public class ScalarExample {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {6, 7, 8, 9, 10};
int[] result = new int[5];
for (int i = 0; i < arr1.length; i++) {
result[i] = arr1[i] + arr2[i];
}
// Print result
for (int value : result) {
System.out.print(value + " ");
}
}
}Pretty straightforward!
There is something to note here which is very obvious. You perform one addition at a time. So, in the above case since the array size is 5 you perform 5 operations sequentially through 5 CPU instructions.
This is called a scalar operation.
What if you could do this addition in a single CPU instruction and the 5 elements are added at the same time?











