자바 스크립트에서 "약한 참조"를 만들 수 있습니까?
자바 스크립트에서 다른 개체에 대한 "약한 참조"를 만드는 방법이 있습니까? 다음은 약한 참조가 무엇인지 설명하는 위키 페이지입니다. 다음은 Java로 설명하는 또 다른 기사입니다. 누구든지 자바 스크립트 에서이 동작을 구현하는 방법을 생각할 수 있습니까?
JavaScript에서 weakref에 대한 언어 지원이 없습니다. 수동 참조 계산을 사용하여 직접 롤링 할 수 있지만 특히 매끄럽지는 않습니다. 프록시 래퍼 객체를 만들 수 없습니다. JavaScript 객체에서는 가비지 수집 될시기를 알 수 없기 때문입니다.
따라서 'weak reference'는 add-reference 및 remove-reference 메소드를 사용하여 간단한 조회에서 키 (예 : 정수)가되며, 더 이상 수동으로 추적되는 참조가 없으면 항목을 삭제하여 향후 조회를 계속 사용할 수 있습니다. null을 반환하는 키입니다.
이것은 실제로 weakref는 아니지만 동일한 문제 중 일부를 해결할 수 있습니다. 일반적으로 복잡한 웹 애플리케이션에서 DOM 노드 또는 이벤트 핸들러와 이와 관련된 객체 (예 : 클로저) 사이에 참조 루프가있을 때 브라우저 (일반적으로 IE, 특히 이전 버전)에서 메모리 누출을 방지하기 위해 수행됩니다. 이러한 경우 전체 참조 계수 체계가 필요하지 않을 수도 있습니다.
NodeJS에서 JS를 실행할 때 https://github.com/TooTallNate/node-weak을 고려할 수 있습니다 .
진정한 약한 참조, 아니요, 아직은 아닙니다 (그러나 브라우저 제작자는 주제를보고 있습니다). 그러나 약한 참조를 시뮬레이션하는 방법에 대한 아이디어가 있습니다.
개체를 구동하는 캐시를 만들 수 있습니다. 객체가 저장 될 때 캐시는 객체가 차지할 메모리 양을 예측합니다. 이미지 저장과 같은 일부 항목의 경우 이것은 간단합니다. 다른 사람들에게는 이것이 더 어려울 것입니다.
객체가 필요할 때 캐시에 요청합니다. 캐시에 객체가 있으면 반환됩니다. 없으면 항목이 생성되고 저장되고 반환됩니다.
약한 참조는 예측 된 총 메모리 양이 특정 수준에 도달하면 항목을 제거하는 캐시에 의해 시뮬레이션됩니다. 검색 빈도에 따라 가장 적게 사용되는 항목을 예측하고, 가져온 시간에 따라 가중치를 부여합니다. 항목을 생성하는 코드가 클로저로 캐시에 전달되는 경우 '계산'비용도 추가 될 수 있습니다. 이렇게하면 캐시가 구축하거나 생성하는 데 매우 비싼 항목을 보관할 수 있습니다.
삭제 알고리즘이 핵심입니다.이 오류가 발생하면 가장 인기있는 항목을 제거 할 수 있기 때문입니다. 이것은 끔찍한 성능을 유발합니다.
캐시가 저장된 객체에 대한 영구 참조 가있는 유일한 객체 인 한, 위의 시스템은 진정한 약한 참조의 대안으로 잘 작동합니다.
참고 용입니다. JavaScript에는 없지만 ActionScript 3 (ECMAScript이기도 함)에는 있습니다. Dictionary 의 생성자 매개 변수를 확인하십시오 .
JL235 가 위에서 제안한 것처럼 캐싱 메커니즘을 사용하여 약한 참조를 에뮬레이트하는 것이 합리적입니다. 약한 참조가 기본적으로 존재하는 경우 다음과 같은 동작을 관찰합니다.
this.val = {};
this.ref = new WeakReference(this.val);
...
this.ref.get(); // always returns val
...
this.val = null; // no more references
...
this.ref.get(); // may still return val, depending on already gc'd or not
캐시를 사용하면 다음을 관찰 할 수 있습니다.
this.val = {};
this.key = cache.put(this.val);
...
cache.get(this.key); // returns val, until evicted by other cache puts
...
this.val = null; // no more references
...
cache.get(this.key); // returns val, until evicted by other cache puts
참조 보유자로서 값을 참조 할 때 어떤 가정도해서는 안됩니다. 이는 캐시를 사용하는 것과 다르지 않습니다.
마침내 그들은 여기에 있습니다. 아직 브라우저에서 구현되지는 않았지만 곧 구현 될 예정입니다.
https://v8.dev/features/weak-references
업데이트 : 2019 년 9 월
It is not possible to use weak references yet, but most likely soon it will be possible, as WeakRefs in JavaScript are Work In Progress. Details below.
Proposal
Proposal in now in Stage 3 which means that it has complete specification and that further refinement will require feedback from implementations and users.
The WeakRef proposal encompasses two major new pieces of functionality:
- Creating weak references to objects with the WeakRef class
- Running user-defined finalizers after objects are garbage-collected, with the FinalizationGroup class
Use cases
A primary use for weak references is to implement caches or mappings holding large objects, where it’s desired that a large object is not kept alive solely because it appears in a cache or mapping.
Finalization is the execution of code to clean up after an object that has become unreachable to program execution. User-defined finalizers enable several new use cases, and can help prevent memory leaks when managing resources that the garbage collector doesn't know about.
Source and further reading
https://github.com/tc39/proposal-weakrefs
https://v8.dev/features/weak-references
EcmaScript 6 (ES Harmony) has a WeakMap object. Browser support amongst modern browsers is pretty good (the last 3 versions of Firefox, chrome and even an upcoming IE version support it).
http://www.jibbering.com/faq/faq_notes/closures.html
ECMAScript uses automatic garbage collection. The specification does not define the details, leaving that to the implementers to sort out, and some implementations are known to give a very low priority to their garbage collection operations. But the general idea is that if an object becomes un-referable (by having no remaining references to it left accessible to executing code) it becomes available for garbage collection and will at some future point be destroyed and any resources it is consuming freed and returned to the system for re-use.
This would normally be the case upon exiting an execution context. The scope chain structure, the Activation/Variable object and any objects created within the execution context, including function objects, would no longer be accessible and so would become available for garbage collection.
Meaning there are no weak ones only ones that no longer become available.
참고URL : https://stackoverflow.com/questions/266704/is-it-possible-to-create-a-weak-reference-in-javascript
'code' 카테고리의 다른 글
.NET에서 null의 해시 코드가 항상 0이면 (0) | 2020.09.17 |
---|---|
POST 작업에서 뷰 모델을 도메인 모델에 다시 매핑하는 방법은 무엇입니까? (0) | 2020.09.17 |
GD vs ImageMagick vs Gmagick for jpg? (0) | 2020.09.17 |
geom_smooth () 사용 가능한 메소드는 무엇입니까? (0) | 2020.09.17 |
PastryKit 프레임 워크 란 무엇입니까? (0) | 2020.09.17 |