programing tip

JavaScript 객체를 빠르게 지우는 방법은 무엇입니까?

itbloger 2020. 6. 4. 19:18
반응형

JavaScript 객체를 빠르게 지우는 방법은 무엇입니까?


JavaScript 배열을 사용하면 단일 할당으로 빈 상태로 재설정 할 수 있습니다.

array.length = 0;

이렇게하면 어레이가 비어 있고 재사용 할 준비가되며 하나의 "조작"즉, 일정한 시간이라는 것을 알 수 있습니다.

JS 객체를 지우는 비슷한 방법이 있습니까? 필드를 삭제하여 삭제할 수 있다는 것을 알고 있습니다.

for (var prop in obj) { if (obj.hasOwnProperty(prop)) { delete obj[prop]; } }

그러나 이것은 선형적인 복잡성을 가지고 있습니다.

객체를 버리고 새 객체를 만들 수도 있습니다.

obj = {};

그러나 새 객체를 "차단 성"으로 만들면 IE6의 가비지 수집에 문제가 발생합니다. ( 여기에 설명 된대로 )


귀하의 질문에 대한 짧은 대답은 아니오라고 생각합니다 (새로운 객체를 만들 수 있습니다).

  1. 이 예제에서 길이를 0으로 설정하면 여전히 가비지 수집을위한 모든 요소가 남습니다.

  2. 자주 사용하는 Object.prototype에 추가 할 수 있습니다. 그렇습니다. 복잡하게 선형 적이지만 나중에 가비지 수집을 수행하지 않는 것이 될 것입니다.

  3. 이것이 가장 좋은 해결책입니다. 귀하의 질문과 관련이 없다는 것을 알고 있습니다. 그러나 IE6 지원을 얼마나 오래 지속해야합니까? 사용을 중단하는 캠페인이 많이 있습니다.

위에 잘못된 것이 있으면 언제든지 수정하십시오.


글쎄, 물건을 너무 쉽게 만들 위험이 있습니다 ...

for (var member in myObject) delete myObject[member];

... 최소한 무서운 괄호를 사용하여 한 줄의 코드로 객체를 청소하는 데 꽤 효과적 인 것 같습니다. 모든 구성원은 가비지로 남지 않고 실제로 삭제됩니다.

분명히 객체 자체를 삭제하려면 여전히 별도의 delete ()를 수행해야합니다.


ES5

ES5 솔루션은 다음과 같습니다.

// for enumerable properties
Object.keys(obj).forEach(function (prop) {
  delete obj[prop];
});

// for all properties
Object.getOwnPropertyNames(obj).forEach(function (prop) {
  delete obj[prop];
});

ES6

ES6 솔루션은 다음과 같습니다.

// for enumerable properties
for (const prop of Object.keys(obj)) {
  delete obj[prop];
}

// for all properties
for (const prop of Object.getOwnPropertyNames(obj)) {
  delete obj[prop];
}

공연

사양에 관계없이 가장 빠른 솔루션은 일반적으로 다음과 같습니다.

// for enumerable properties
var props = Object.keys(obj);
for (var i = 0; i < props.length; i++) {
  delete obj[props[i]];
}

// for all properties of an object with proto chain
var props = Object.getOwnPropertyNames(obj);
for (var i = 0; i < props.length; i++) {
  delete obj[props[i]];
}

// for all properties of shallow/plain object
for (var key in obj) {
  // this check can be safely omitted in modern JS engines
  // if (obj.hasOwnProperty(key))
    delete obj[key];
}

for..in얕은 객체 나 일반 객체에서만 수행해야하는 이유 는 삭제할 수있는 자체 속성이 아니라 프로토 타입으로 상속 된 속성을 통과하기 때문입니다. 그것은 확실히 알 수없는 경우 객체는 일반입니다 for함께 Object.getOwnPropertyNames더 나은 선택입니다.


당신은 이것을 시도 할 수 있습니다. 아래 함수는 객체 속성의 모든 값을 undefined로 설정합니다. 중첩 된 객체와 함께 작동합니다.

var clearObjectValues = (objToClear) => {
    Object.keys(objToClear).forEach((param) => {
        if ( (objToClear[param]).toString() === "[object Object]" ) {
            clearObjectValues(objToClear[param]);
        } else {
            objToClear[param] = undefined;
        }
    })
    return objToClear;
};

그래서 당신의 질문을 요약하면 : 가능한 한 IE6 GC 버그와 관련된 문제를 피하고 싶습니다. 이 버그에는 두 가지 원인이 있습니다.

  1. 가비지 콜렉션은 많은 할당 마다 한 번씩 발생합니다 . 따라서 할당을 많이할수록 GC가 더 자주 실행됩니다.
  2. The more objects you've got ‘in the air’, the more time each Garbage Collection run takes (since it'll crawl through the entire list of objects to see which are marked as garbage).

The solution to cause 1 seems to be: keep the number of allocations down; assign new objects and strings as little as possible.

The solution to cause 2 seems to be: keep the number of 'live' objects down; delete your strings and objects as soon as you don't need them anymore, and create them afresh when necessary.

To a certain extent, these solutions are contradictory: to keep the number of objects in memory low will entail more allocations and de-allocations. Conversely, constantly reusing the same objects could mean keeping more objects in memory than strictly necessary.


Now for your question. Whether you'll reset an object by creating a new one, or by deleting all its properties: that will depend on what you want to do with it afterwards.

You’ll probably want to assign new properties to it:

  • If you do so immediately, then I suggest assigning the new properties straightaway, and skip deleting or clearing first. (Make sure that all properties are either overwritten or deleted, though!)
  • If the object won't be used immediately, but will be repopulated at some later stage, then I suggest deleting it or assigning it null, and create a new one later on.

There's no fast, easy to use way to clear a JScript object for reuse as if it were a new object — without creating a new one. Which means the short answer to your question is ‘No’, like jthompson says.


Something new to think about looking forward to Object.observe in ES7 and with data-binding in general. Consider:

var foo={
   name: "hello"
};

Object.observe(foo, function(){alert('modified');}); // bind to foo

foo={}; // You are no longer bound to foo but to an orphaned version of it
foo.name="there"; // This change will be missed by Object.observe()

So under that circumstance #2 can be the best choice.


You can delete the props, but don't delete variables. delete abc; is invalid in ES5 (and throws with use strict).

You can assign it to null to set it for deletion to the GC (it won't if you have other references to properties)

Setting length property on an object does not change anything. (it only, well, sets the property)

참고URL : https://stackoverflow.com/questions/684575/how-to-quickly-clear-a-javascript-object

반응형