java list几种性能比较

时间:2022-10-27 19:20:57
public class MyDemo {
    private static final Logger log = LoggerFactory.getLogger(MyDemo.class);
    public static void main(String[] args) {
        List<Integer> list = new ArrayList();
        for(int i =0;i<1000000;i++){
            list.add(i);
        }

        long end = System.currentTimeMillis();
        for(Integer i:list){
            new String();
        }
        long start = System.currentTimeMillis();
        log.info("for :::::>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:"+(start-end));

        for(int i=0;i<list.size();i++){
            new String();
        }
        end = System.currentTimeMillis();
        log.info("for size  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:"+(end-start));

        list.stream().map(s->{
            return  new String();
        });
        start = System.currentTimeMillis();
        log.info("stream()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:"+(start-end));

        list.forEach(s->{
                    new String();

                }
        );
        end = System.currentTimeMillis();
        log.info("foreach  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:"+(end-start));
    }


}

结果输出:

[INFO] for :::::>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:7
[INFO] for size  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:5
[INFO] stream()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:48
[INFO] foreach  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:7

综合结果:for size>for>foreach>stream()