Copy

Shallow Copy vs Deep Copy

์–•์€ ๋ณต์‚ฌ Shallow Copy

  • ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ•ฉ๋‹ˆ๋‹ค.

  • ํ•œ์ชฝ์˜ ์ˆ˜์ •์ด ์ด๋ฃจ์–ด์ง€๋ฉด ๋‹ค๋ฅธ ํ•œ ์ชฝ์—๋„ ์˜ํ–ฅ์ด ๊ฐ‘๋‹ˆ๋‹ค.

๊นŠ์€ ๋ณต์‚ฌ Deep Copy

  • ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑ ํ•ฉ๋‹ˆ๋‹ค.

  • ์„œ๋กœ ๊ฐ„ ์˜ํ–ฅ์ด ์—†์Šต๋‹ˆ๋‹ค.

Java ์—์„œ ์‚ฌ์šฉ๋˜๋Š” Copy ๋ฉ”์†Œ๋“œ์˜ ๋น„๊ต

Method
Primitive Type Copy
Non-Primitive Type Copy
Speed

System.arraycopy()

Deep

Shallow

Fastest

Object.clone()

Deep

Shallow

Fast

Arrays.copyOf()

Deep

Shallow

Fast

Using for

Depend on code

Depend on code

Slow

  • Primitive Type ์€ ๊ฐ’ ๊ทธ ์ž์ฒด์ด๊ธฐ ๋•Œ๋ฌธ์— Deep Copy ๋ฅผ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค.

  • Non-Primitive Type ์€ ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ•˜๋ฉฐ Swallow Copy ๋ฅผ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค.

clone()

clone() ์€ shallow copy ๋ฅผ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค. deep copy ๋ฅผ ์œ„ํ•ด์„œ๋Š” Cloneable ๋ฅผ ๊ตฌํ˜„ํ•˜๊ฑฐ๋‚˜ ํ•ด์ฃผ๊ฑฐ๋‚˜ new ๋ฅผ ํ†ตํ•ด deep copy ๋ฅผ ํ•ด์ฃผ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

์ƒ˜ํ”Œ ์ฝ”๋“œ

  • Cloneable ๋ฅผ implements ํ•˜์ง€ ์•Š์€ ์‚ฌ์šฉ์ž ์ •์˜ ํด๋ž˜์Šค

    • clone : shallow copy

    • forCopy : deep copy

origin
clone
forCopy
import java.util.Arrays;

public class test {
  public static class Temp {
    public int a;
    public Object obj;

    public Temp(int a) {
      this.a = a;
      this.obj = new Object();
    }

    public int getA() {
      return a;
    }
  }

  public static void main(String[] args) {
    Temp[] origin = new Temp[]{new Temp(1), new Temp(2), new Temp(280), new Temp(1500), new Temp(40000)};
    Temp[] arrayCopy = new Temp[5];

    System.arraycopy(origin, 0, arrayCopy, 0, 5);

    Temp[] clone = origin.clone();
    Temp[] copyOf = Arrays.copyOf(origin, 5);
    Temp[] forCopy = new Temp[5];
    
    for (int i = 0; i < origin.length; i++) {
      forCopy[i] = new Temp(origin[i].getA());
    }
  }
}

Last updated

Was this helpful?