-
[Java] String operator + , String.concat() 비교 해보자용어정리 2022. 1. 12. 17:58
알고리즘 문제를 풀다가 concat()연산과 String + 연산의 성능차이가 궁금해 졌습니다.
https://yourknow.tistory.com/41
[알고리즘] 프로그래머스 괄호 변환 Java(자바)
- 문제 https://programmers.co.kr/learn/courses/30/lessons/60058# 코딩테스트 연습 - 괄호 변환 카카오에 신입 개발자로 입사한 "콘"은 선배 개발자로부터 개발역량 강화를 위해 다른 개발자가 작성한 소스 코..
yourknow.tistory.com
알고 있던 지식은 Buffer > 메소드 > + 순이었는데
Java 1.5 이상 부터는 + 연산을 StringBuilder로 바꿔서 진행한다는 글이 있더군요
[JAVA] 문자열 붙이는 방식의 차이(concat, +, StringBuilder)
자바에서 String타입을 붙일 때 사용하는 방법은 다양하다. 기본 연산자인 + 를 비롯하여 String Builder , concat 모두 들어보거나 써본 용어일 것이다. 근데 동작 방식에 어떤 차이가 있을까? 먼저 결과
devdy.tistory.com
위의 경험과 달라서 분석을 나름대로 해보았습니다!!
틀린곳이 있다면 알려주시고 즐겁게 봐주셨으면 좋겠습니다 ㅎㅎ..
String str = "abc";
str = str.concat("def"); 라고 했을 때
public String concat(String str) { if (str.isEmpty()) { return this; } return StringConcatHelper.simpleConcat(this, str); }concat()을 호출하면 simpleConCat() 으로 이동을 합니다.
this는 "abc"
str은 "def" 가 되겠죠?
@ForceInline static String simpleConcat(Object first, Object second) { String s1 = stringOf(first); String s2 = stringOf(second); // start "mixing" in length and coder or arguments, order is not // important long indexCoder = mix(initialCoder(), s1); indexCoder = mix(indexCoder, s2); byte[] buf = newArray(indexCoder); // prepend each argument in reverse order, since we prepending // from the end of the byte array indexCoder = prepend(indexCoder, buf, s2); indexCoder = prepend(indexCoder, buf, s1); return newString(buf, indexCoder); }위 함수에서 stringOf()를 통해 toString()을 호출하여 s1,s2에 객체를 생성하여 문자를 할당하는것으로 보입니다.
mix() 함수에선 s1,s2를 차례로 넣어주면서 인코딩, 오버플로우와 s1+s2의 문자열 길이를 구해 줍니다.
그다음 indexCoder의 길이만큼 byte[] buf의 초기화를 진행합니다.
그리고 prepand()를 통해 문자열을 거꾸로 생성하는데 여기서 getBytes()를 통해 진행됩니다.
static String newString(byte[] buf, long indexCoder) { // Use the private, non-copying constructor (unsafe!) if (indexCoder == LATIN1) { return new String(buf, String.LATIN1); } else if (indexCoder == UTF16) { return new String(buf, String.UTF16); } else { throw new InternalError("Storage is not completely initialized, " + (int)indexCoder + " bytes left"); } }이 후 newString() 을통해 내부적으로
new String()을 호출하며 스트링 객체를 생성합니다.
java string + 연산 : 어떻게 동작하는지 알아봅시다.
Java의 String은 불변 객체입니다. String a와 String b가 있을 때, a = a+b; 이 문장은 어떻게 동작할까요? 결론부터 말하자면, 비효율적으로 동작합니다. 어디서 오버헤드가 많이 발생하는지 천천히 분
codingdog.tistory.com
String + 연산은 해당 블로그를 참조하면 처음 시작할때 String,valueOf()를 호출하고 StringBuilder의 append 그리고 getByte()로 StringBuilder의 value에 문자를 할당하고 마지막으로 toString()의 과정을 거치게 됩니다.
위의 과정을 봤을 때 큰 차이점은 concat()은 3번의 new String() 호출
String operator 는 처음 String.valueOf()의 과정이라고 생각하고 여기서 차이가 나는거 같습니다.
프로그래머스가 켜져 있어서 아래의 코드로 코드를 실행해본 결과입니다.
1ms = 0.001초
정말 작은 차이이지만 속도면에서는 concat()이 유리하다고 생각이 드네요
- 결론
가독성이 +가 좋아 습관을 바꿀듯하다
허나 최적화 속도를 다른 코드보다 조금이라고 빠르게 하고 싶다면 StringBuilder객체 생성을 최소화 한다고 했을 때
StringBuilder > concat() > String operator를 쓸듯하다.
String answer = ""; String temp = "def"; String str = "abc"; //for(int i=0; i<1000; i++) // str = str.concat(temp); for(int i=0; i<1000; i++) str = str + temp;
concat() 
String operator '용어정리' 카테고리의 다른 글
AWS IAM (2) 2023.05.22 관계형데이터 베이스 vs 비관계형 데이터베이스 (0) 2023.05.13 블록스토리지 vs 파일스토리지 vs 객체 스토리지 (0) 2023.05.11 IDE란? (1) 2021.01.05