Java – is it more efficient to scan an array once for multiple predicates or multiple times for a single predicate

I have an int array of 1000 elements I need to extract the sizes of various subgroups in the array (how many are even, odd, greater than 500, etc.)

I can use the for loop and a bunch of if statements to try to add count variables for each match, for example:

for(int i = 0; i < someArray.length i++) {
    if(conditionA) sizeA++;
    if(conditionB) sizeB++;
    if(conditionC) sizeC++;
    ...
}

Or I can do something lazier, such as:

supplier<IntStream> ease = () -> Arrays.stream(someArray);
int sizeA = ease.get().filter(conditionA).toArray.length;
int sizeB = ease.get().filter(conditionB).toArray.length;
int sizeC = ease.get().filter(conditionC).toArray.length;
...

The benefits of achieving this goal in the second way seem to be limited to readability, but will efficiency be greatly impacted? Could it be more efficient? I guess it comes down to iterating the array once. Four conditions are always better than four iterations, one condition at a time (assuming that the conditions are independent) I know this special example. The second method has a lot of additional method calls. I'm sure it won't improve efficiency

Solution

preface:

>As @ kayaman pointed out, it may not be important for a small array (1000 elements). > The right way to deal with such things is to optimize after completing the working code and working benchmark, and then look at the real hot spots after analyzing the code

However, assuming that this is worth the cost of optimization, the first version may be faster than the second version for two reasons:

>The overhead of incrementing and testing indexes occurs only once in the first version and three times in the second version. > For arrays that are too large to fit into the memory cache, the first version will require fewer memory reads than the second version Since memory access is often a bottleneck (especially on multi-core machines), this may be important. > Streams adds additional performance overhead compared to simple array iterations

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>