본문 바로가기
Java/JAVA에 대하여

int vs Integer

by lms0806 2024. 6. 9.
728x90
반응형

int와 Integer의 차이는 원시타입과 객체타입로 보시면 됩니다.

그러나 둘다 숫자를 저장한다는 공통점을 가지고 있습니다.

'그러면 int대신에 Integer로 전부 통일시키면 괜찮지 않을까?' 라는 생각을 하게 되었고, 이를 기반으로 시간 테스트를 진행해 보았습니다.

 

가장먼저 각 값들을 n번 선언해보았습니다.

		int a = 0;
		long beforeTime = System.currentTimeMillis();
		for(int i = 0; i < 1000000000; i++) {
			a = 0;
		}
		System.out.println(System.currentTimeMillis() - beforeTime);
		
		Integer b = 0;
		beforeTime = System.currentTimeMillis();
		for(int i = 0; i < 1000000000; i++) {
			b = 0;
		}
		System.out.println(System.currentTimeMillis() - beforeTime);
  int Integer
시간(ms) 1 4

 

이번엔 값 선언 후, +1 연산을 수행해 보았습니다.

 

		int a = 0;
		long beforeTime = System.currentTimeMillis();
		for(int i = 0; i < 1000000000; i++) {
			a++;
		}
		System.out.println(System.currentTimeMillis() - beforeTime);
		
		Integer b = 0;
		beforeTime = System.currentTimeMillis();
		for(int i = 0; i < 1000000000; i++) {
			b++;
		}
		System.out.println(System.currentTimeMillis() - beforeTime);
  int Integer
시간(ms) 1 1622

 

그러면 ArrayList에 int형 값을 저장하게 되면 boxing되서 Integer타입으로 변경됩니다.

그러나 .get()함수를 사용하게 되면, 다시 unboxing이 되서 int타입으로 변경되게 됩니다.

 

이러면 .get()함수를 통해서 값을 어떻게 가져올까? 라고 내부 코드를 확인해 보았습니다.

    public E get(int index) {
        Objects.checkIndex(index, size);
        return elementData(index);
    }
    
    public static
    int checkIndex(int index, int length) {
        return Preconditions.checkIndex(index, length, null);
    }
    
    @IntrinsicCandidate
    public static <X extends RuntimeException>
    int checkIndex(int index, int length,
                   BiFunction<String, List<Number>, X> oobef) {
        if (index < 0 || index >= length)
            throw outOfBoundsCheckIndex(oobef, index, length);
        return index;
    }

checkIndex를 통해 index값이 존재하는지 확인합니다.

index의 값이 0보다 작지않고, list의 length보다 크지 않은 경우, elemetData(index)를 통해 해당 값을 가져옵니다.

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

여기서 사용한 @SuppressWarnings("unchecked")이 무엇인지 알아본 결과

 

@SuppressWarnings("unchecked") 어노테이션을 사용하면 컴파일러가 이 경고를 무시하도록 할 수 있습니다.

라고 되어 있었습니다.

 

왜 컴파일러의 경고를 무시하고 값을 가져오도록 되어 있는지에 대해서는 다음에 좀 더 알아보도록 하겠습니다.

728x90
반응형

'Java > JAVA에 대하여' 카테고리의 다른 글

알아두면 좋은 for, switch  (0) 2024.06.02
문자열 다루기  (0) 2024.04.14
LinkedHashSet에 대하여  (0) 2023.11.01
HashSet 내부  (2) 2022.09.24
JAVA의 깊은 복사, 얕은 복사  (0) 2021.12.30

댓글