简体   繁体   中英

Saving memory and CPU in java loops

this (obvious) code i've writen works well, but for testing purposes, i should make it work for a "one million" sized array in a reasonable time by saving CPU Cycles and saving as much memory as i can.
any suggestions please?
!!! the array is arranged in ascending order !!!

import java.util.Arrays;

class A {
static boolean exists(int[] ints, int k) {
    for(int integer : ints){
        if(integer == k){
            return true; 
        }
    }
    return false;
}

You could use a Set<Integer> that relies on hashing rather than an array where you iterate sequentially.

static boolean exists(Set<Integer> ints, int k) {
     return ints.contains(k);
}

You could convert the array to a Set and pass it to the method as many times as required :

Set<Integer> set = Arrays.stream(ints).boxed().collect(Collectors.toSet());
boolean isExist = exists(set, 15);
 ...
isExist = exists(set, 5005);
 ...
isExist = exists(set, 355);

由于您的数组是按升序排列的,因此您可以做的一件事是进行二进制搜索而不是线性搜索。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM