Since it is troublesome to turn for, if you basically write all the list creation with stream To my senior, "stream is actually a for statement, so it's a waste of memory." I got a review saying that I was a little irritated, so I checked it.
Try using a simple memory measurement method
DecimalFormat f1 = new DecimalFormat("#,###KB");
DecimalFormat f2 = new DecimalFormat("##.#");
long free = Runtime.getRuntime().freeMemory() / 1024;
long total = Runtime.getRuntime().totalMemory() / 1024;
long max = Runtime.getRuntime().maxMemory() / 1024;
long used = total - free;
double ratio = (used * 100 / (double)total);
String info =
"Java memory information:total=" + f1.format(total) + "、" +
"amount to use=" + f1.format(used) + " (" + f2.format(ratio) + "%)、" +
"Maximum available="+f1.format(max);
System.out.println(info);
Java memory information:total=125,952KB, usage=1,997KB (1.6%), Maximum available=1,864,192KB
List<Integer> list = new ArrayList<>();
List<Integer> devided1 = new ArrayList<>();
List<Integer> devided2 = new ArrayList<>();
List<Integer> devided3 = new ArrayList<>();
for(int i = 1; i<=10000 ; i++) {
list.add(i);
}
for(Integer num : list) {
if(num % 3 == 1) {
devided1.add(num);
}
if(num % 3 == 2) {
devided2.add(num);
}
if(num % 3 == 0) {
devided3.add(num);
}
}
Java memory information:total=125,952KB, usage=2,665KB (2.1%), Maximum available=1,864,192KB
List<Integer> devided1 = list.stream()
.filter(i -> i%3 ==1)
.collect(Collectors.toList());
List<Integer> devided2 = list.stream()
.filter(i -> i%3 ==2)
.collect(Collectors.toList());
List<Integer> devided3 = list.stream()
.filter(i -> i%3 ==0)
.collect(Collectors.toList());
Java memory information:total=125,952KB, usage=3,995KB (3.2%), Maximum available=1,864,192KB
I'm sorry to say cheeky seniors. After all, if you repeat the same process three times, it will consume memory. As far as this number is seen, it seems that the usage amount of for is smaller even if the same processing is performed once.
I have doubts about the term "real for sentence" After all, it is not always good to use a new one.
However, I think the latter is the readability and ease of writing.
Recommended Posts