Tại sao list.size()>0
chậm hơn list.isEmpty()
bằng Java? Nói cách khác, tại sao isEmpty()
thích hợp hơn size()>0
?Tại sao list.size()> 0 chậm hơn list.isEmpty() trong Java?
Khi tôi nhìn vào thực hiện trong ArrayList
, sau đó nó trông giống như tốc độ nên được như vậy:
ArrayList.size()
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size;
}
ArrayList.isEmpty()
/**
* Returns <tt>true</tt> if this list contains no elements.
*
* @return <tt>true</tt> if this list contains no elements
*/
public boolean isEmpty() {
return size == 0;
}
Nếu chúng ta chỉ viết một chương trình đơn giản để dành thời gian y cả hai phương pháp, trường hợp đó size()
sẽ mất thêm isEmpty()
trong mọi trường hợp, tại sao lại như vậy?
Đây là Mã thử nghiệm của tôi;
import java.util.List;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
List l=new Vector();
int i=0;
for(i=0;i<10000;i++){
l.add(new Integer(i).toString());
}
System.out.println(i);
Long sTime=System.nanoTime();
l.size();
Long eTime=System.nanoTime();
l.isEmpty();
Long eeTime=System.nanoTime();
System.out.println(eTime-sTime);
System.out.println(eeTime-eTime);
}
}
Ở đây eTime-sTime>eeTime-eTime
trong mọi trường hợp. Tại sao?
@ JLR: Có tôi chấp nhận quan điểm của bạn, có lỗ hổng, như thử nghiệm cả hai phương pháp trong 2 dự án riêng biệt và cả hai đều cho kết quả tương tự nhau. Thanx để xóa bỏ sự nghi ngờ của tôi –