Skip to content

JavaScript에서 shallow copy 피하기 #3

Open

Description

@voidmatcha

Array

var origin = [1, 2];
var copy = origin.slice(0);

Activity

  1. self-assigned this
    on Feb 27, 2021
  2. changed the title [-]Javascript에서 shallow copy 피하기[/-] [+]JavaScript에서 shallow copy 피하기[/+] on Feb 27, 2021
  3. voidmatcha commented on Mar 12, 2021

    @voidmatcha
    MemberAuthor

    Array(...).fill([]); 혹은 Array(N).fill({}); 하면 채워진 배열 혹은 객체의 reference가 복사되는 형태가 된다. 이를 해결하기 위해서는 아래와 같은 방법들이 있다.

    // Array(...)로 생성 후 for문 사용 - 가장 빠름
    const arr = Array(...);
    for (let i = 0; i < arr.length; i++) {
      arr[i] = [];
    }
    
    // 배열 리터럴로 생성 후 Array.push - 2배 느림
    const arr = [];
    for (let i = 0; i < arr.length; i++) {
      arr.push([]);
    }
    
    
    // destructuring 사용 - 5배 느림
    [...Array(...)].map(() => []);
    
    // forEach - 6배 느림
    const arr = Array(...);
    arr.forEach((value, index) => {
     arr[i] = [];
    });
    
    // map 사용 - 11배 느림
    Array(...).fill().map(() => []);
    
    // Array.from()을 사용 - 30배 느림
    Array.from(Array(...), () => []));

    reference: https://stackoverflow.com/a/43461022

  4. voidmatcha commented on Mar 13, 2021

    @voidmatcha
    MemberAuthor

    Array() 생성자를 선언할 때 new 연사자를 함께 사용하는 것이 맞는걸까? 공식문서를 보면 항상 new 연산자와 함께 선언하고 있어서 궁금해서 찾아봤다.

    ECMA-262 문서를 보면 아래와 같이 설명하고 있다. 결론적으론 new 연산자 없이 선언해도 상관없다.

    also creates and initializes a new Array object when called as a function rather than as a constructor. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.

    reference: https://scottwhittaker.net/posts/javascript-array-constructor-called-as-a-function/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions