Что такое сборка "мусора" JavaScript?

Вам может потребоваться разработать собственный инструмент форматирования. Допустим, поле для i3 начинается в start. Подготовьте строку из первых двух полей, обрежьте или расширьте ее, если необходимо, и добавьте строку для третьего элемента:

s12 = f"{i1:<5}{i2:<5}"
start = 8

(s12[:start] if start <= len(s) else s + " " * (start - len(s))) + f"{i3}"
#'1234 45 856'
start=12
(s12[:start] if start <= len(s) else s + " " * (start - len(s))) + f"{i3}"
#'1234 45     856'
295
задан 14 May 2009 в 05:58
поделиться

6 ответов

Эрик Липперт некоторое время назад написал подробное сообщение в блоге на эту тему (дополнительно сравнивая его с VBScript ). Точнее, он писал о JScript , который является собственной реализацией ECMAScript Microsoft, хотя и очень похож на JavaScript. Я предполагаю, что вы можете предположить, что подавляющее большинство поведения будет таким же для движка JavaScript Internet Explorer. Конечно, реализация будет варьироваться от браузера к браузеру, хотя я подозреваю, что вы можете взять ряд общих принципов и применить их к другим браузерам.

Цитата с той страницы:

JScript использует не связанный с поколениями mark-and-sweep garbage collector. It works like this:

  • Every variable which is "in scope" is called a "scavenger". A scavenger may refer to a number, an object, a string, whatever. We maintain a list of scavengers -- variables are moved on to the scav list when they come into scope and off the scav list when they go out of scope.

  • Every now and then the garbage collector runs. First it puts a "mark" on every object, variable, string, etc – all the memory tracked by the GC. (JScript uses the VARIANT data structure internally and there are plenty of extra unused bits in that structure, so we just set one of them.)

  • Second, it clears the mark on the scavengers and the transitive closure of scavenger references. So if a scavenger object references a nonscavenger object then we clear the биты на нераскладчике и на все, к чему это относится. (Я используя слово «закрытие» в в другом смысле, чем в моем предыдущем post.)

  • На данный момент мы знаем, что все все еще отмеченная память выделена память, которая не может быть достигнута никакими путь от любой переменной в области видимости. Все этих объектов поручено разрушают себя, что разрушает any circular references.

The main purpose of garbage collection is to allow the programmer not to worry about memory management of the objects they create and use, though of course there's no avoiding it sometimes - it is always beneficial to have at least a rough idea of how garbage collection works.

There are a few particular points of which to be aware. The Apple developer site has some guidelines on the matter. Two important ones from there:

  • Use delete statements. Whenever you create an object using a new statement, pair it with a delete statement. This ensures that all of the memory associated with the object, including its property name, is available for garbage collection. The delete statement is discussed more in “Freeing Objects.”
  • Use the var keyword. Any variable created without the var keyword is created at the global scope and is never eligible for garbage collection, presenting the opportunity for a memory leak.

I would imagine that the practices should apply to all JavaScript engines (in different browsers), though because this is from an Apple site, they may be somewhat specific to Safari. (Perhaps someone could clarify that?)

Hope that helps.

191
ответ дан 23 November 2019 в 01:36
поделиться

Остерегайтесь циклических ссылок, когда задействованы объекты DOM:

Шаблоны утечки памяти в JavaScript

Помните, что память может быть освобождена только при отсутствии активных ссылок на объект. Это обычная ошибка с замыканиями и обработчиками событий, так как некоторые JS-движки не проверяют, на какие переменные на самом деле ссылаются во внутренних функциях, а просто сохраняют все локальные переменные включающих функций.

Вот простой пример:

function init() {
    var bigString = new Array(1000).join('xxx');
    var foo = document.getElementById('foo');
    foo.onclick = function() {
        // this might create a closure over `bigString`,
        // even if `bigString` isn't referenced anywhere!
    };
}

Наивный Реализация JS не может собирать bigString , пока есть обработчик событий. Есть несколько способов решить эту проблему, например, установка bigString = null в конце init () ( delete не будет работать для локальных переменных и функции аргументы:

52
ответ дан 23 November 2019 в 01:36
поделиться

Good quote taken from a blog

The DOM component is "garbage collected", as is the JScript component, which means that if you create an object within either component, and then lose track of that object, it will eventually be cleaned up.

For example:

function makeABigObject() {
var bigArray = new Array(20000);
}

When you call that function, the JScript component creates an object (named bigArray) that is accessible within the function. As soon as the function returns, though, you "lose track" of bigArray because there's no way to refer to it anymore. Well, the JScript component realizes that you've lost track of it, and so bigArray is cleaned up--its memory is reclaimed. The same sort of thing works in the DOM component. If you say document.createElement('div'), or something similar, then the DOM component creates an object for you. Once you lose track of that object somehow, the DOM component will clean up the related.

16
ответ дан 23 November 2019 в 01:36
поделиться

To the best of my knowledge, JavaScript's objects are garbage collected periodically when there are no references remaining to the object. It is something that happens automatically, but if you want to see more about how it works, at the C++ level, it makes sense to take a look at the WebKit or V8 source code

Typically you don't need to think about it, however, in older browsers, like IE 5.5 and early versions of IE 6, and perhaps current versions, closures would create circular references that when unchecked would end up eating up memory. In the particular case that I mean about closures, it was when you added a JavaScript reference to a dom object, and an object to a DOM object that referred back to the JavaScript object. Basically it could never be collected, and would eventually cause the OS to become unstable in test apps that looped to create crashes. In practice these leaks are usually small, but to keep your code clean you should delete the JavaScript reference to the DOM object.

Usually it is a good idea to use the delete keyword to immediately de-reference big objects like JSON data that you have received back and done whatever you need to do with it, especially in mobile web development. This causes the next sweep of the GC to remove that object and free its memory.

13
ответ дан 23 November 2019 в 01:36
поделиться

"In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory used by objects that will never be accessed or mutated again by the application."

All JavaScript engines have their own garbage collectors, and they may differ. Most time you do not have to deal with them because they just do what they supposed to do.

Writing better code mostly depends of how good do you know programming principles, language and particular implementation.

4
ответ дан 23 November 2019 в 01:36
поделиться

Что такое сборка мусора JavaScript?

проверьте this

Что важно для веб-программиста о сборке мусора в JavaScript, для написания лучшего кода?

В Javascript вы не заботитесь о распределении и освобождении памяти. Вся проблема возложена на интерпретатор Javascript. В Javascript по-прежнему возможны утечки, но это ошибки интерпретатора. Если вам интересна эта тема, вы можете прочитать больше в www.memorymanagement.org

1
ответ дан 23 November 2019 в 01:36
поделиться
Другие вопросы по тегам:

Похожие вопросы: