Java

[Effective Java] ์•„์ดํ…œ 63. ๋ฌธ์ž์—ด ์—ฐ๊ฒฐ์€ ๋Š๋ฆฌ๋‹ˆ ์ฃผ์˜ํ•˜๋ผ.

quedevel 2023. 3. 28. 11:50
728x90
๋ฐ˜์‘ํ˜•

๐ŸŽฏ ์•„์ดํ…œ 63. ๋ฌธ์ž์—ด ์—ฐ๊ฒฐ์€ ๋Š๋ฆฌ๋‹ˆ ์ฃผ์˜ํ•˜๋ผ.

๋ฌธ์ž์—ด ์—ฐ๊ฒฐ ์—ฐ์‚ฐ์ž๋กœ ๋ฌธ์ž์—ด n๊ฐœ๋ฅผ ์ž‡๋Š” ์‹œ๊ฐ„์€ n^2์— ๋น„๋ก€ํ•œ๋‹ค.

  • ๋ฌธ์ž์—ด ์—ฐ๊ฒฐ์„ ์ž˜๋ชป ์‚ฌ์šฉํ•œ ์˜ˆ - ๋Š๋ฆฌ๋‹ค!
public String statement(){
    String result = "";
    for(int i = 0; i < numItems(); i++)
        result += lineForItem(i);
    return result;
}

ํ’ˆ๋ชฉ์ด ๋งŽ์„ ๊ฒฝ์šฐ ์ด ๋ฉ”์„œ๋“œ๋Š” ์‹ฌ๊ฐํ•˜๊ฒŒ ๋Š๋ ค์งˆ ์ˆ˜ ์žˆ๋‹ค. ์„ฑ๋Šฅ์„ ํฌ๊ธฐํ•˜๊ณ  ์‹ถ์ง€ ์•Š๋‹ค๋ฉด String ๋Œ€์‹  StringBuilder๋ฅผ ์‚ฌ์šฉํ•˜์ž.

  • StringBuilder๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฌธ์ž์—ด ์—ฐ๊ฒฐ ์„ฑ๋Šฅ์ด ํฌ๊ฒŒ ๊ฐœ์„ ๋œ๋‹ค.
public String statement2(){
    StringBuilder b = new StringBuilder(numItems() * LINE_WIDTH);
    for(int i = 0; i < numItems(); i++)
        b.append(lineForItem(i));
    return b.toString();
}

์ฐธ๊ณ  ์ž๋ฃŒ

Joshua Bloch, ใ€ŽEffective Java 3/Eใ€, ๊ฐœ์•ž๋งต์‹œ ์˜ฎ๊น€, ํ”„๋กœ๊ทธ๋ž˜๋ฐ์ธ์‚ฌ์ดํŠธ(2018)
http://www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9788966262281&orderClick=LEa&Kc=

728x90
๋ฐ˜์‘ํ˜•