Javascript.RU

Эвристическое переименование свойств

Где-то посередине между продвинутым и обычным сжатием находится эвристическое переименование.

При его использовании Google Closure Compiler переименует все свойства объекта и прототипа, кроме тех, которые начинаются с _подчеркивания.

Эти свойства оптимизатор считает публичными (да-да, не приватными а публичными) и не переименует вообще.

Например, объявим класс Animal. Он будет состоять из конструктора и методов в прототипе.

/** @constructor */
function Animal() { }
Animal.prototype = {
  speed: 10,
   
  calculateDistance: function(time, speed) {
    return time*speed;
  },
  
  _setSpeed: function(speed) {
    this.speed = speed
  },  
  
  _run: function(time) {     
     alert(this.calculateDistance(time, this.speed))
  }
}

После обычной оптимизации:

function Animal() {
}
Animal.prototype = {speed:10, calculateDistance:function(a, b) {
  return a * b
}, _setSpeed:function(a) {
  this.speed = a
}, _run:function(a) {
  alert(this.calculateDistance(a, this.speed))
}};

После оптимизации с эвристическим переименованием:

function Animal() {
}
Animal.prototype = {a:10, b:function(a, b) {
  return a * b
}, _setSpeed:function(a) {
  this.a = a
}, _run:function(a) {
  alert(this.b(a, this.a))
}};

Как видите, все свойства, кроме _setSpeed, _run были переименованы.

При этом компилятор учел, что speed переименовано в a и также переименовал this.speed в this.a.

Оптимизация касается прототипов и объектов в литеральной нотации {prop: 'val', ...}.

Для определения, какие свойства экспортируемые, а какие нет, Closure Compiler использует класс GoogleCodingConvention, метод isExported которого можно поменять на удобный вам. Например, наоборот сделать экспортируемыми методы без подчеркивания.

Переименованием занимается класс RenamePrototypes, логика методов canRenamePrototypeProperty и canRenameObjLitProperty также в вашем распоряжении.

Чтобы включить эвристическое переименование, можно создать соответствующий флаг.

Этот флаг включен в сборку MyCompiler под именем property_renaming_policy:

--property_renaming_policy=AGGRESSIVE_HEURISTIC

Есть также значение HEURISTIC, но в нем вообще мало смысла, даже рассматривать нет резона.

Продвинутый режим сжатия не совместим (и его не стоит использовать) с эвристическим переименованием, так как он представляет собой следующую ступень агрессивности - переименовывает все подряд.

То есть, по возрастающей идут:

  • Простая оптимизация - сжимаются локальные свойства.
  • Эвристическое переименование (при простой оптимизации) - дополнительно сжимаются все свойства, кроме начинающихся с подчеркивания.
  • Продвинутая оптимизация - сжимается все.

Возможно, эвристическое переименование было промежуточным этапом в разработке компилятора, до продвинутой оптимизации.

Мне было интересно разобраться в этом режиме, но сложно придумать ему применение. Если вам придет в голову что-то дельное - напишите


Автор: vlad0 (не зарегистрирован), дата: 13 января, 2010 - 12:56
#permalink

попробовал я --property_renaming_policy=AGGRESSIVE_HEURISTIC
на моем проекте вываливается с ошибкой "ERROR - Rename prototypes and inline variables cannot be used together"

в сорцах нашел упоминание
if (isInliningForbidden()) {
// In old renaming schemes, inlining a variable can change whether
// or not a property is renamed. This is bad, and those old renaming
// schemes need to die.
return new ErrorPass(compiler, CANNOT_USE_PROTOTYPE_AND_VAR);


Автор: Илья Кантор, дата: 13 января, 2010 - 16:12
#permalink

Видимо вы врубили одновременно ADVANCED оптимизацию.


Автор: Гость (не зарегистрирован), дата: 7 мая, 2010 - 12:11
#permalink

Подтверждаю - если при компиляции указаны опции AGGRESSIVE_HEURISTIC или HEURISTIC - не работает и вываливается с той же ошибкой.
ERROR - Rename prototypes and inline variables cannot be used together

--compilation_level SIMPLE_OPTIMIZATIONS

В режиме же

--compilation_level WHITESPACE_ONLY

просто ничего не делается.


Автор: Гость (не зарегистрирован), дата: 7 мая, 2010 - 12:21
#permalink

Закомментировал вызовы isInliningForbidden - все равно ничего не происходит. Опция совершенно мёртвенькая.


Автор: Zenitchik, дата: 15 июля, 2013 - 12:45
#permalink

В какой версии это ещё работало?


Автор: Durring (не зарегистрирован), дата: 22 июня, 2020 - 11:54
#permalink

что speed переименовано в a и также переименовал this.speed в this.a. cookie clicker


Автор: tiny fishing (не зарегистрирован), дата: 1 марта, 2021 - 13:09
#permalink

Wonderful post. This post is one of the best posts according to my point of view. Your work is so good and impressive. Thanks for it tiny fishing


Автор: justicehwrknz807 (не зарегистрирован), дата: 10 января, 2022 - 10:29
#permalink

There is a certain unity to this work that I really appreciate. Please keep creating this amazing content. Commercial Concrete Contractors Tampa


Автор: bolukat (не зарегистрирован), дата: 24 января, 2022 - 09:29
#permalink

Thank you very much for sharing your knowledge and information; it has greatly aided me in my job and personal life. run 3


Автор: steven sanders (не зарегистрирован), дата: 15 апреля, 2022 - 06:03
#permalink

On mobile devices, the site performs very well. If you find it difficult to copy a ringtone from your computer and then transfer it to your phone, you can use Dzwoneknatelefon on your phone to do it for you. After inputting the song name or sound type in the search box, you will see a list of ringtones sorted by category or popularity. Select the tone that appeals to you and click Download. Simply open the ringtone that you wish to download, select the option "Save to Phone" and then choose a unique name for it. The downloaded ringtone will be on your phone and the following steps will be simple. Please keep note of the folder where you saved the ringtone.


Автор: antiguans2000, дата: 30 июня, 2022 - 17:21
#permalink

This is interesting! We should try this one. www.backpay.biz/phoenix, drywall repair


Автор: Jason Hawker (не зарегистрирован), дата: 18 июля, 2022 - 13:33
#permalink

The Suonerietelefono is the perfect way to add a personal touch to your mobile phone. With over 200 free ringtones to choose from, you can find the perfect one for any situation. Whether you're looking for something fun and energetic for a night out, or something more subdued for work or school, there's a Suonerietelefono ringtone for you. And best of all, they're all free to download. So what are you waiting for? Find your perfect ringtone today with Suonerietelefono!


Автор: antiguans2000, дата: 2 сентября, 2022 - 09:33
#permalink

Thank you for sharing this helpful info. We can use this in radon mitigation dayton ohio work.


Автор: Ruiz Angelina (не зарегистрирован), дата: 17 сентября, 2022 - 13:24
#permalink

KlingeltoneMp3 is the best place to find free MP3 ringtones. With a huge selection of ringtones divided into different categories, you're sure to find your favorite in minutes. Whether you're looking for Android, Iphone, Marimba Remix, Samsung, Tiktok, Holiday, Electronica, Classic, Message Tones, Sound Effects, Uncategorized, Whatsapp, HipHop, Funny, Pop, Synthetic or Entertainment ringtones, KlingeltoneMp3 has you covered.


Автор: Winifred Beck (не зарегистрирован), дата: 23 сентября, 2022 - 04:49
#permalink

traditional arcade a new version of snake io is released for playing special online live events. In this well-liked mobile version of the cherished arcade game, slither to the top of the leaderboard!


Автор: 바카라사이트 (не зарегистрирован), дата: 23 сентября, 2022 - 04:58
#permalink

Your writing is perfect and complete. 바카라사이트 However, I think it will be more wonderful if your post includes additional topics that I am thinking of. I have a lot of posts on my site similar to your topic. Would you like to visit once?


Автор: Alejandro11 (не зарегистрирован), дата: 7 октября, 2022 - 11:50
#permalink

Para descargar los últimos tonos de llamada gratis aquí con una sola acción, ya tienes un tono de llamada personalizado por separado.


Автор: BaileyDaugherty (не зарегистрирован), дата: 18 ноября, 2022 - 06:26
#permalink

Interesting, and thank you; I appreciate the insight. gartic phone


Автор: 카지노사이트 (не зарегистрирован), дата: 18 ноября, 2022 - 06:41
#permalink

There must have been many difficulties in providing this information. 카지노사이트 Nevertheless, thank you for providing such high-quality information.


Автор: Lauriel Racher (не зарегистрирован), дата: 1 декабря, 2022 - 09:31
#permalink

Are you looking for an edge in your next fighting game? Well, look no further than the Shadow Fight 2 Mod APK! This exciting mod gives you access to unlimited resources, so you can upgrade your characters and gear to the max. Plus, with the built-in auto-win feature, you'll always come out on top! So why wait? Download the Shadow Fight 2 Mod APK today and become the ultimate fighter!


Автор: Alejandro11 (не зарегистрирован), дата: 13 декабря, 2022 - 07:34
#permalink

descargue los últimos tonos de llamada 2022 para su teléfono móvil aquí proporcione los últimos tonos de llamada gratis actualizados


Автор: Гость (не зарегистрирован), дата: 15 мая, 2023 - 13:14
#permalink

All fnaf games are free. You can play online on our website using smart devices with an internet connection. All your visits are free.


Автор: Diana Howard (не зарегистрирован), дата: 14 июня, 2023 - 10:06
#permalink

A great game called bad ice cream is getting hot this summer. Please try this game and let me know what you think about it.


Автор: donna1205 (не зарегистрирован), дата: 5 июля, 2023 - 05:13
#permalink

Glad you set up this slither io forum. It is very useful for everyone.


Автор: Гость (не зарегистрирован), дата: 24 июля, 2023 - 06:26
#permalink

The wave of undead legions is around, do you think it will be easy? Vampire Survivors game is a true zombie whirlwind, with classic arcade graphics of the 80s, 90s, and gameplay of shooting zombies like the old spaceship shooting style, it can only be Vampire Survivors. Sometimes you will forget that you are playing zombie shooting but think you are entering some retro classic game world. This is also a rare feature of Vampire Survivors compared to many other zombie games.


Автор: MichaelWilliams (не зарегистрирован), дата: 27 июля, 2023 - 12:28
#permalink

Let the clicker frenzy begin! Capybara Clicker offers an addictive gameplay loop, stunning visuals, and a captivating soundtrack that will keep you coming back for more.


Автор: Гость (не зарегистрирован), дата: 22 сентября, 2023 - 06:07
#permalink

Minecraftle is a refreshing and innovative take on word puzzles. Get ready to test your crafting skills and word knowledge in one exciting game.


Автор: DOLLY (не зарегистрирован), дата: 22 сентября, 2023 - 08:18
#permalink

Kudos to you for addressing such an important topic. We need more content like this.
https://balakrishnangroup.com/


Автор: blabling2 (не зарегистрирован), дата: 26 сентября, 2023 - 13:39
#permalink

connect 4 - grain games


Автор: tommchris (не зарегистрирован), дата: 1 ноября, 2023 - 10:02
#permalink

The article in this forum is very good, this article is very helpful for me. Nice to read your post. If you can, take a moment to play game Uno Online one of the most exciting games


Автор: ew (не зарегистрирован), дата: 23 марта, 2024 - 07:42
#permalink

Great blog. It was interesting reading your article. This book was really fun for me to read. I saved it and can't wait to read more from it. Keep up your great work!
play capybara clicker game


Автор: antiguans2000, дата: 11 апреля, 2024 - 11:53
#permalink

Your home's beauty will not be the only thing enhanced by a roof restoration auckland. However, it also raises the energy efficiency of your house.


Отправить комментарий

Приветствуются комментарии:
  • Полезные.
  • Дополняющие прочитанное.
  • Вопросы по прочитанному. Именно по прочитанному, чтобы ответ на него помог другим разобраться в предмете статьи. Другие вопросы могут быть удалены.
    Для остальных вопросов и обсуждений есть форум.
P.S. Лучшее "спасибо" - не комментарий, как все здорово, а рекомендация или ссылка на статью.
Содержание этого поля является приватным и не предназначено к показу.
  • Адреса страниц и электронной почты автоматически преобразуются в ссылки.
  • Разрешены HTML-таги: <strike> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <u> <i> <b> <pre> <img> <abbr> <blockquote> <h1> <h2> <h3> <h4> <h5> <p> <div> <span> <sub> <sup>
  • Строки и параграфы переносятся автоматически.
  • Текстовые смайлы будут заменены на графические.

Подробнее о форматировании

CAPTCHA
Антиспам
17 + 0 =
Введите результат. Например, для 1+3, введите 4.
 
Текущий раздел
Поиск по сайту
Содержание

Учебник javascript

Основные элементы языка

Сундучок с инструментами

Интерфейсы

Все об AJAX

Оптимизация

Разное

Дерево всех статей

Последние комментарии
Последние темы на форуме
Forum