1 нояб. 2015 г.

Как разводить гремлинов

Классы ошибок, обнаруживаемые с помощью gremlins.js:
  • Ошибки вёрстки. Гремлину scroller иногда удаётся проскроллить совершенно неожиданные элементы страницы/приложения и загнать элементы интерфейса далеко за пределы видимой области. Обнаруживается визуально.
  • Reflow/repaint performance. После некоторых действий пользователя FPS может упасть из-за неидеальной вёрстки (scroll или незначительное изменение стиля ведёт к полному reflow документа и repaint всей видимой области) или объёмных вычислений в JavaScript (например, dirty checking в Angular-приложении). При падении FPS ниже 10 в консоли выдаётся сообщение.
  • Ошибки concurrency. Некоторые действия приложение может выполнять асинхронно, например, в интерфейсе с несколькими вкладками при переключении между ними такие действия, как отсылка запроса на сервер, очистка неактивной вкладки, создание объектов активной вкладки, обработка ответа сервера, отрисовка содержимого активной вкладки, переключение заголовков вкладок в принципе могут выполняться в разные моменты времени. Если кликать не спеша, с паузами, то порядок действий практически никогда не нарушится. Такие гремлины, как clicker, помогают обнаружить ошибки, если интервал между кликами становится сравним с интервалами между асинхронными действиями, и порядок выполнения кода может сломаться.
  • Ошибки алгоритмов/бизнес-логики. Гремлины formFiller и clicker могут вводить данные и нажимать на кнопки в совершенно непредсказуемой последовательности, и у какой-нибудь сложной валидации данных от этого может сорвать крышу.

20 окт. 2015 г.

JavaScript benchmarking tools


JetStream

JetStream includes benchmarks from the SunSpider 1.0.2 and Octane 2 JavaScript benchmark suites. It also includes benchmarks from the LLVM compiler open source project, compiled to JavaScript using Emscripten 1.13. It also includes a benchmark based on the Apache Harmony open source project's HashMap and a port of the CDx benchmark, hand-translated to JavaScript.

These benchmarks cover both classical performance measurements — like Martin Richards's machine and language independent benchmark (richards) and the Dhrystone synthetic computing benchmark (dry.c) — and real-world examples — like the Mozilla open source project's PDF renderer (pdfjs), the Box2D JavaScript physics engine (box2d), and the jQuery and Closure JavaScript libraries (code- first-load, code-multi-load).

Octane 2.0

Octane 2.0 is a modern benchmark that measures a JavaScript engine’s performance by running a suite of tests representative of today’s complex and demanding web applications. Octane‘s goal is to measure the performance of JavaScript code found in large, real-world web applications, running on modern mobile and desktop browsers.

Octane v1 focused on execution throughput, but in today's highly interactive applications (e.g. games, UI-rich web applications) reducing jankiness (what we call "ensuring low latency") is just as important. The V8 team wants to reduce compiler and garbage collection latency, so we included specific measures for those in Octane 2.0. In order to accomplish that we instrumented two existing tests, Mandreel and Splay, so that they now produce a latency score together with the existing speed score from Octane v1.

Octane 2.0 adds a test to measure how VMs perform on asm.js-like code. The test is taken directly from the zlib sample code from Mozilla's Emscripten test suite. To simulate complex data structure- and memory-intensive applications, we added a test derived from Microsoft's TypeScript compiler. The result measures how fast TypeScript compiles itself.

19 авг. 2015 г.

Глубина стека JavaScript (дубль 3)

Продолжение (первая часть, вторая часть)

Баг в Firefox подсказал, что глубина стека зависит ещё и от метода вызова (fn(), fn.call(), fn.apply()), и от контекста функции (fn.call(null) или fn.call(this)), и от платформы (Firefox 39/Win vs. Firefox 39/Linux). В одном из комментариев было указано, что при переходе с прямого вызова fn() на fn.call() в версии Firefox под Linux глубина стека уменьшалась с 7000 до 500.

Добавил в скрипт подсчёт глубины стека при использовании call.

Результаты

Windows 7 64-bit:
Chrome 44:    глубина стека не зависит от метода вызова
Safari 5.1.7: глубина стека не зависит от метода вызова
IE11:         fn() 2800..2300, fn.call() 1900..1700
Firefox 39:   fn() 8400..4800, fn.call() 7200..5600

Windows 10:
Edge:         fn() 5000,80026..81336, fn.call() 5207..5291
Firefox Dev. edition 43.0a2: fn() 3500..3000, fn.call() 4400..3300

Интересные факты:

  • В Firefox/Win при отсутствии передаваемых аргументов прямой вызов fn() иногда занимает меньше памяти в стеке, чем fn.call(this), при наличии аргументов - всегда fn.call(this, arg) занимает меньше, чем fn(arg).
  • В Firefox/Linux fn.call() в некоторых случаях даёт на порядок меньшую глубину стека.
  • В IE11 fn.call() даёт в 1.3 - 1.4 раза меньшую глубину стека.
  • В Edge первый запуск может дать глубину стека fn() около 5000, последующие запуски дают глубину стека около 80000


12 мая 2015 г.

Remove ads in Skype 7.x


  1. Update to the latest version of Skype (Help - Check for Updates)
  2. Open IE11
  3. Open Menu - Internet Options
  4. Go to Security tab
  5. Select "Restricted sites" icon
  6. Click on "Sites" button
  7. Add apps.skype.com to the list of restricted sites
  8. Press "Close" button
  9. Press OK
  10. Open Skype. Now it should be free of advertisements
Or, if you are seasoned firewall user, just block apps.skype.com in your firewall.

29 апр. 2015 г.

Chrome Canary + IRHydra 2

How to retrieve files for IRHydra 2:

  1. Install Chrome Canary
  2. Go to its installation directory (%LOCALAPPDATA%\Google\Chrome SxS\Application\ on Windows), there should be chrome.exe
  3. Create script with all needed flags:
    @echo off
    chrome.exe --no-sandbox --js-flags="--trace-hydrogen --trace-phase=Z --trace-deopt --code-comments --hydrogen-track-positions --redirect-code-traces"
  4. Run script. Chrome window should open. If needed, dismiss warning about unsupported "sandbox" option.
  5. In that Chrome window go to the URL you want to gather information about.
  6. Close Chrome.
  7. Go to Chrome Canary binary folder (e.g. %LOCALAPPDATA%\Google\Chrome SxS\Application\44.0.2385.0\ on Windows). There should be files "code-*-1.asm" and "hydrogen-*-1.cfg", they are created in pairs for each Chrome process while tracing.
  8. Pick the proper pair of files (usually the latest and biggest ones), move to another folder, delete the rest.
  9. Go to http://mrale.ph/irhydra/2/
  10. Click on folder icon in upper left corner, select those two "code-*-1.asm" and "hydrogen-*-1.cfg" files.

Оптимизация — это культура

Главное правило оптимизации заключается в том, что оптимизация — это культура. Нельзя год фигачить код лопатой, а потом надеяться исправить все проблемы с производительностью за день. Нет простых магических рецептов, а наемные волшебницы и волшебники, которые могут прилететь в голубых вертолетах и внезапно все исправить, стоят очень много эскимо. Нужно постоянно следить за производительностью, точно так же как вы постоянно прогоняете тесты. Нужно знать базовые алгоритмы и фундаментальные вещи об устройстве платформы, под которую вы разрабатываете. Ну и самое главное - нужно писать вменяемый код.

http://mrale.ph/blog/2015/04/12/jsunderhood.html