СРАВНИТЕЛЬНЫЙ АНАЛИЗ СРЕД ИСПОЛНЕНИЯ ANDROID-ПРИЛОЖЕНИЙ — DALVIK И ART

Разбираемся в тонкостях программ Art и Dalvik

Версия Android 4.4 помимо расширенной функциональности, предлагает пользователям принципиально новый способ обработки данных. В предыдущих версиях компиляция файлов выполнялась в среде Dalvik. Это виртуальная машина Android, которая переводит зашифрованный файл в язык программирования, доступный считыванию процессором мобильного устройства. В новой версии СО для смартфонов, корпорацией Google используется среда выполнения ART, которая по уверению разработчиков обладает большей производительностью. ART или Dalvik? Попробуем разобраться в этой статье.

  • Twitter
  • Blogger

Cреда выполнения ART, с помощью которой вы сможете повысить производительность смартфона

Учитывая, что среда Dalvik и ART практически идентичны, то отдать предпочтение одной из них довольно сложно. Наверное, всё зависит от мобильного устройства, которое вы используете.

ПОСМОТРЕТЬ ВИДЕО

Если позволяет объём памяти, лучше выбирать ART. Этот инструмент не перегружает процессор и быстрее работает с приложениями. Кроме того, это новая система, которая будет дорабатываться, и обрастать новыми возможностями.

How ART works

ART uses ahead-of-time (AOT) compilation, and starting in Android 7.0
(Nougat or N), it uses a hybrid combination of AOT, just-in-time (JIT)
compilation, and profile-guided compilation. The combination of all these
compilation modes is configurable and will be discussed in this section. As an
example, Pixel devices are configured with the following compilation flow:

  1. An application is initially installed without any AOT compilation. The
    first few times the application runs, it will be interpreted, and methods
    frequently executed will be JIT compiled.
  2. When the device is idle and charging, a compilation daemon runs to
    AOT-compile frequently used code based on a profile generated during the
    first runs.
  3. The next restart of an application will use the profile-guided code and
    avoid doing JIT compilation at runtime for methods already compiled. Methods
    that get JIT-compiled during the new runs will be added to the profile, which
    will then be picked up by the compilation daemon.

ART comprises a compiler (the tool) and a runtime
() that is loaded for starting the Zygote. The
tool takes an APK file and generates one or more
compilation artifact files that the runtime loads. The number of files, their
extensions, and names are subject to change across releases, but as of the
Android O release, the files being generated are:

  • : contains the uncompressed DEX code of the
    APK, with some additional metadata to speed up verification.
  • : contains AOT compiled code for methods in the
    APK.
  • : contains ART internal
    representations of some strings and classes listed in the APK, used to speed
    application startup.

JIT vs. AOT

When you install an app on your Android today it will use the Dalvik VM to compile and run it. This process utilizes a concept called just-in-time, or JIT. It’s a great concept, but one that has quite a bit of overhead when you first launch apps.

Let’s take the process apart and see how it works. You download and install an app to your phone or tablet. It sits there on your internal storage until you launch it. When you do, Android pulls all the uncompiled data together, compiles it, and loads the app into memory (RAM). As long as the app is there, after the initial load time, it’s pretty snappy.  If you use a task killer, manually kill the app, or navigate away and load up other apps, the first app is unloaded, freeing up the RAM it had been using. When you go back to it, it’s got to go through the whole process all over again.

ART should increase performance by… “Moon River! … Yeah, breathe easy. Using the whole fist, Doc?!”

Android 4.4 KitKat, at least on the Nexus 5, includes a new runtime call “Android runtime”, ART. Though it’s not a very creative name, it is pretty creative in what it does. Unlike JIT, which must compile every app whenever it’s loaded, ART works on a concept called ahead-of-time (AOT) compilation. With ART, when you download and install an app it automatically pre-compiles. This takes up more space on your device and takes longer to initially install when compared to Dalvik. However, apps launch quicker and are arguably faster when run using ART rather than Dalvik. What’s more, since less time is required to run apps, your processor doesn’t get worked as hard and your battery life may benefit as a result.

All that sounds great, right? It is! Or, rather, it will be.

Преимущества и недостатки ART

Новая виртуальная машина обрела жизнь вместе с Android 4.4 KitKat, однако на презентации ей не уделили должного внимания. Причиной этого является то, что ART все еще находится на экспериментальной стадии. Впрочем, хотя и Dalvik используется в качестве машины по умолчанию, переключиться на Android Runtime можно уже сейчас.
Однако не спешите это делать. Сначала необходимо ознакомиться с особенностям новой версии.

Наиболее заметным преимуществом ART является новый тип компиляции, который получил название Ahead-Of-Time. Читатели, знающие английский язык, наверняка сразу же догадались, в чем дело. А дело в том, что процесс преобразования кода в новой версии осуществляется до запуска приложения — еще во время установки. Соответственно, сразу же вырисовываются несколько минусов, о которых, справедливости ради, стоит упомянуть. Это, во-первых, более длительный процесс установки, а во-вторых, больший объем конечного размера приложения. Еще один недостаток является следствием незрелости ART: виртуальная машина на данный момент работает далеко не со всеми приложениями.

Впрочем, список заслуг куда более значимый. Это, к примеру, более плавная работа интерфейса и более быстрая загрузка приложений. Кроме того, поскольку процесс компиляции осуществляется лишь единожды, он не будет в дальнейшем нагружать процессор, что станет причиной улучшенной автономности устройства.

Переключиться на виртуальную машину ART в меню разработчика могут владельцы устройств под управлением Android 4.4 с процессором Snapdragon.

Faster native methods

Faster native calls to the Java Native Interface (JNI) are available using
the and annotations. These built-in ART runtime
optimizations speed up JNI transitions and replace the now deprecated
!bang JNI notation. The annotations have no effect on non-native
methods and are only available to platform Java Language code on the
(no Play Store updates).

The annotation supports non-static methods. Use this
if a method accesses a as a parameter or return value.

The annotation provides an even faster way to run
native methods, with the following restrictions:

  • Methods must be static—no objects for parameters, return values, or an
    implicit .
  • Only primitive types are passed to the native method.
  • The native method does not use the and
    parameters in its function definition.
  • The method must be registered with instead of
    relying on dynamic JNI linking.

can improve native method performance up to 3x, and
up to 5x. For example, a JNI transition measured
on a Nexus 6P device:

Java Native Interface (JNI) invocation Execution time (in nanoseconds)
Regular JNI 115
!bang JNI 60
35
25

Declare classes required in the primary DEX file

When building each DEX file for a multidex app, the build tools perform
complex decision-making to determine which classes are needed in the primary DEX
file so that your app can start successfully. If any class that's required
during startup is not provided in the primary DEX file, then your app crashes
with the error .

This shouldn't happen for code that's accessed directly from your app
code because the build tools recognize those code paths, but it can happen when
the code paths are less visible such as when a library you use has
complex dependencies. For example, if the code uses introspection or invocation
of Java methods from native code, then those classes might not be recognized as
required in the primary DEX file.

So if you receive , then you
must manually specify these additional classes as required in the primary DEX
file by declaring them with the or the property in your build type. If a class is matched in either
the or the file, then that class
is added to the primary DEX file.

multiDexKeepFile property

The file you specify in should contain one class per line, in the
format . For example, you can create a
file called that looks like this:

com/example/MyClass.class
com/example/MyOtherClass.class

Then you can declare that file for a build type as follows:

android {
    buildTypes {
        release {
            multiDexKeepFile file('multidex-config.txt')
            ...
        }
    }
}

Remember that Gradle reads paths relative to the file,
so the above example works if is in the same directory
as the file.

multiDexKeepProguard property

The file uses the same format as Proguard and supports the entire
Proguard grammar. For more information about Proguard format and grammar, see the
section
in the Proguard manual.

The file you specify in should contain
options in any valid ProGuard syntax. For example,
. You can create a file called
that looks like this:

-keep class com.example.MyClass
-keep class com.example.MyClassToo

If you want to specify all classes in a package, the file looks like this:

-keep class com.example.** { *; } // All classes in the com.example package

Then you can declare that file for a build type as follows:

android {
    buildTypes {
        release {
            multiDexKeepProguard file('multidex-config.pro')
            ...
        }
    }
}

Что использовать dalvik или art. ART идет на смену Dalvik

Нашлось место для многих изменений и усовершенствований. Большинство из них сразу же бросается в глаза даже рядовому пользователю данной системы. Это, конечно же, установка в качестве стандартного месседжера приложения Hangouts, переделанное меню набора номеров и добавление клавиатуры Emoji. Бывалые же приверженцы Android наверняка ощутят прилив производительности в сравнении с более старыми ее релизами. Однако не обошлось и без скрытых сторон, которые, согласно логике, должны представлять интерес лишь для разработчиков. Впрочем, значимость одного из подобных нововведений особенно велика. Кроме того, вскоре оно коснется каждого из нас, а потому умолчать о его подробностях было бы просто преступлением.Наверное, многие из вас хотя бы краем уха слышали о том, что в Android KitKat появился особый режим. Суть его заключается в более быстром запуске приложений и в более стабильном и плавном их выполнении. Возможно, попытки разобраться в данном вопросе самостоятельно не были увенчаны успехом. Оно и неудивительно: слова «виртуальная машина» и «компиляция» способны испугать кого-угодно, особенно, если информация потребляется из англоязычного источника. Для решения данной проблемы мы решили разобраться в сути вопроса самостоятельно, изложив его в максимально доступном виде.

Dexlayout

Dexlayout is a library introduced in Android 8.0 to analyze dex files and
reorder them according to a profile. Dexlayout aims to use runtime profiling
information to reorder sections of the dex file during idle maintenance
compilation on device. By grouping together parts of the dex file that are
often accessed together, programs can have better memory access patterns from
improved locality, saving RAM and shortening start up time.

Since profile information is currently available only after apps have been run,
dexlayout is integrated in dex2oat's on-device compilation during idle
maintenance.

В чём преимущество новой среды ART

Инструменты ART и Dalvik выполняют схожие функции, поэтому выявить преимущества новой виртуальной машины можно лишь путём сравнения. Рассмотрим достоинства и недостатки каждой среды выполнения.

Среда выполнения Dalvik устанавливается с 2008 года. По сути, этот инструмент является ровесником операционной системы. Этот инструмент использует способ компиляции файлов JUST IN TIME. Суть заключается в том, что преобразователь кода активируется вместе с запуском приложения. Недостаток такого способа компиляции заключается в повышенном потреблении ресурсов процессора при запуске программ. В результате некоторые используемые файлы откровенно тормозят или вылетают.

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

Важно! При обновлении приложения кэш становится неактуальным, поэтому полностью избавиться от зависания приложений не получится!

ART в Android появился сравнительно недавно. В версии 4.4 новая среда проходила тестирование, а в Android 5.0 установлена по умолчанию. Разработчики учли ошибки предыдущей версии, поэтому работа новой среды выполнения заметно улучшилась. Например:

  • Изменился процесс компиляции. Виртуальное устройство работает по принципу AHEAD OF TIME. Расшифровка файлового кода происходит не в момент запуска, а в процессе установки. Это снижает потребление ресурсов оперативной памяти.
  • Стали поддерживаться 64-х битные ОС.
  • Виртуальная машина быстрее удаляет информационный мусор, соответственно зависания системы сведены к минимуму.

Среди выявленных недостатков выделяется следующее:

  • Приложения дольше устанавливаются.
  • Виртуальный инструмент занимает больше оперативной памяти.

More inlining

Since Android 6.0, ART can inline any call within the same dex files, but could
only inline leaf methods from different dex files. There were two reasons for
this limitation:

  1. Inlining from another dex file requires to use the dex cache of that other
    dex file, unlike same dex file inlining, which could just re-use the dex cache
    of the caller. The dex cache is needed in compiled code for a couple of
    instructions like static calls, string load, or class load.
  2. The stack maps are only encoding a method index within the current dex file.

To address these limitations, Android 8.0:

  1. Removes dex cache access from compiled code (also see section «Dex cache
    removal»)
  2. Extends stack map encoding.

Как работает Dalvik и как будет работать ART

DalvikVM работает в реальном времени, то есть преобразует код в аппаратный «на ходу» (Just-In-Time). Таким образом очень нагружая процессор.
А вот прекомпилятор ART, будет преобразовывать код сразу при установке приложения.

Плюсы
прекомпилятора ART:

+ Повышение скорости выполнения «тяжёлых» задач.
+ Даёт возможность чаще отключать неиспользуемые ядра процессора. Таки образом может увеличится время автономной работы устройства.

Минусы конечно же тоже есть. Один, по-моему, главный это увеличение размера установленной программы. Конечно же обладатели устройств с 32 ГБ памяти на борту этого не по чувствуют. Но ведь есть же ещё устройства даже с 8 ГБ на борту…

JIT compilation

JIT compilation involves the following activities:

Figure 2. Profile-guided compilation.

  1. The user runs the app, which then triggers ART to load the
    file.
    • If the file (the AOT binary for the
      file) is available, ART uses it directly. Although files are
      generated regularly, they don't always contain compiled code (AOT binary).
    • If the file does not contain compiled code, ART runs
      through JIT and the interpreter to execute the file.
  2. JIT is enabled for any application that is not compiled according to the
    compilation filter (which says «compile as much as you can
    from the app»).
  3. The JIT profile data is dumped to a file in a system directory that only
    the application can access.
  4. The AOT compilation () daemon parses that file to drive
    its compilation.
    Figure 3. JIT daemon activities.

The Google Play service is an example used by other applications that behave
similar to shared libraries.

Что такое среда выполнения приложений виртуальная машина

Обсуждение Dalvik и ART невозможно без понимания азов, поэтому сначала поговорим о виртуальной машине как таковой. Среда выполнения приложений — это набор инструкций, выполняемых для перевода кода приложения в код, понятный компьютеру. Виртуальная машина задействуется, даже не являясь частью основной программы. В целом, все «управляемые» компьютерные языки (Java в Android, С# в Windows Phone, ECMAScript в браузерах) требуют такую среду для понимания языка, на котором написано приложение.

Android использует виртуальную машину для выполнения DEX-файлов (аналог EXE в Windows), которые содержатся в APK-архиве Android-приложения. Существует сразу два преимущества такого решения. Во-первых, каждое приложение выполняется в системе, изолированной от ядра ОС, так что последнее чувствует себя более-менее в безопасности. Во-вторых, использование виртуальной машины открывает дорогу кросс-платформенным приложениями, то есть приложение может работать на ARM-смартфоне, MIPS-планшете или x86-компьютере.

Как известно, все это время в Android использовалась виртуальная машина Dalvik, с которой наверняка встречался каждый, кто хоть немного вникал в особенности ОС.

Whats a virtual machine

Physical machines are just that: physical. They’re tangible, you can touch them. They’re the computer under your desk, the notebook on your lap, the server in the closet down the hall. When you think of a computer, this is what you’re probably picturing.

Virtual machines?! “Heyya! It’s all ball bearings nowadays!”

Virtual machines aren’t physical, but they do run on physical hardware. Confused yet? Say your desktop computer is a Mac and you’re running some flavor of OS X. You’ve got a couple programs that you want to run that don’t work in your OS. You might want to load up a couple virtual machines and install Windows into one and Linux into another. These virtual machines emulate all the hardware that is needed for you to install and run an operating system. You can literally run a complete Windows environment in a window on your Mac, and the same goes for Linux or almost any other operating system. Pretty cool, eh?

Other than the obvious, one of the main advantages of utilizing a virtual machine is the physical separation of each environment. Apps that run in the VM are separate from those running in the host environment. Viruses, malware, and even crashed apps are all kept apart from your main OS, insulating you from the implications of such occurrences. Another advantage of VMs is the ability to run programs written for one architecture on a box that runs something different. For example, the ability to run programs compiled to run on an ARM-based CPU when your computer is running an Intel-based processor.

To better illustrate that last point, let’s take a look back at Windows Mobile and Pocket PC. Back then developers would write their apps, then compile them for several platforms: ARM version 4, Intel XScale, MIPS, or SH3 CPUs. Each processor had its own advantages and disadvantages, but they all required separately compiled versions of every app that you hoped to run on any one of them. When Pocket PC 2002 was announced, Microsoft standardized on ARM.

Today’s Androids use a specialized virtual machine in which they run their apps. Developers write code which you, the end user, install from the Play Store or some other source. This code is mostly uncompiled. That means it’s slower than compiled code would be, but your device gets the “insulation” advantages that VMs provide, and developers don’t have to worry about re-compiling their code to run on some other CPU — like a new tablet, PC,  TV, watch, or even a rice cooker.

Преимущества и недостатки Dalvik

Dalvik, как и все в этом мире, неидеальна. Причиной периодических подергиваний интерфейса является тип преобразования кода приложения в аппаратный. Данная машина проделывает это в прямом эфире, а называется такой тип компиляции Just-In-Time. Соответственно, предугадать появление багов практически невозможно, поскольку подобное может произойти в любой момент. Особенно велика вероятность подобного во время первого запуска, когда часть преобразованного кода даже не сохранена в кеше.

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

Компиляция «на ходу» значительно нагружает процессор, однако одновременно с этим позволяет разработчикам не заниматься оптимизацией кода для каждого отдельного процессора и прочих составляющих устройства.

Исправить вышесказанное призвана новая виртуальная машина, которая успела отметиться далеко не самым замысловатым названием — Android Runtime. Или же сокращенно — ART.

Как включить ART на Android

Для того, чтобы включить среду ART, вы должны иметь Android телефон или планшет с версией ОС 4.4.x и процессором Snapdragon, например, Nexus 5 или Nexus 7 2013.

Сначала необходимо включить режим разработчика на Android. Для этого, зайдите в настройки устройства, перейдите в пункт «О телефоне» (О планшете) и несколько раз тапните по полю «Номер сборки», пока не увидите сообщение о том, что стали разработчиком.

После этого в настройках появится пункт «Для разработчиков», а там — «Выберите среду», где и следует установить ART вместо Dalvik, если у вас есть такое желание.

А вдруг и это будет интересно:

About the 64K reference limit

Android app (APK) files contain executable bytecode files in the form
of Dalvik
Executable (DEX) files, which contain the compiled code used to run your app.
The Dalvik Executable specification limits the total number of methods that
can be referenced within a single DEX file to 65,536—including Android
framework methods, library methods, and methods in your own code. In the
context of computer science, the term Kilo, K, denotes 1024 (or
2^10). Because 65,536 is equal to 64 X 1024, this limit is referred to as the
'64K reference limit'.

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik
runtime for executing app code. By default, Dalvik limits apps to a single
bytecode file per APK. In order to get around this
limitation, you can add the multidex support library to your project:

dependencies {
    def multidex_version = "2.0.1"
    implementation 'androidx.multidex:multidex:$multidex_version'
}
   

To view the current versions for this library, see the information about
Multidex on the versions page.

If you aren't using AndroidX, add the following support library
dependency instead:

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

This library becomes part of the primary DEX file of your app and then
manages access to the additional DEX files and the code they contain.
More details are below in the section about how to
.

Multidex support for Android 5.0 and higher

Android 5.0 (API level 21) and higher uses a runtime called ART which
natively supports loading multiple DEX files from APK files. ART
performs pre-compilation at app install time which scans for
files and compiles them into a single
file for
execution by the Android device. Therefore, if your
is 21 or higher multidex is enabled by default,
and you do not need the multidex support library.

For more information on the Android 5.0
runtime, read ART and Dalvik.

Note: When running your app using Android Studio,
the build is optimized for the target devices you deploy to.
This includes enabling multidex when the target devices are running
Android 5.0 and above.
Because this optimization is applied only when deploying your app using Android Studio, you might
still need to for multidex to avoid the
64K limit.

Interpreter performance

Interpreter performance significantly improved in the Android 7.0 release with
the introduction of «mterp» — an interpreter featuring a core
fetch/decode/interpret mechanism written in assembly language. Mterp is
modelled after the fast Dalvik interpreter, and supports arm, arm64, x86,
x86_64, mips and mips64. For computational code, Art's mterp is roughly
comparable to Dalvik's fast interpreter. However, in some situations it can be
significantly — and even dramatically — slower:

  1. Invoke performance.
  2. String manipulation, and other heavy users of methods recognized as
    intrinsics in Dalvik.
  3. Higher stack memory usage.

Android 8.0 addresses these issues.

App resources

An Android app is composed of more than just code—it requires resources that are
separate from the source code, such as images, audio files, and anything relating to the visual
presentation of the app. For example, you can define animations, menus, styles, colors,
and the layout of activity user interfaces with XML files. Using app resources makes it easy
to update various characteristics of your app without modifying code. Providing
sets of alternative resources enables you to optimize your app for a variety of
device configurations, such as different languages and screen sizes.

For every resource that you include in your Android project, the SDK build tools define a unique
integer ID, which you can use to reference the resource from your app code or from
other resources defined in XML. For example, if your app contains an image file named
(saved in the directory), the SDK tools generate
a resource ID named . This ID maps to an app-specific integer, which
you can use to reference the image and insert it in your user interface.

One of the most important aspects of providing resources separate from your source code
is the ability to provide alternative resources for different device
configurations. For example, by defining UI strings in XML, you can translate
the strings into other
languages and save those strings in separate files. Then Android applies the
appropriate language strings
to your UI based on a language qualifier
that you append to the resource directory's name (such as for French string
values) and the user's language setting.

Android supports many different qualifiers for your alternative resources. The
qualifier is a short string that you include in the name of your resource directories in order to
define the device configuration for which those resources should be used. For
example, you should create different layouts for your activities, depending on the
device's screen orientation and size. When the device screen is in portrait
orientation (tall), you might want a layout with buttons to be vertical, but when the screen is in
landscape orientation (wide), the buttons could be aligned horizontally. To change the layout
depending on the orientation, you can define two different layouts and apply the appropriate
qualifier to each layout's directory name. Then, the system automatically applies the appropriate
layout depending on the current device orientation.

For more about the different kinds of resources you can include in your application and how to
create alternative resources for different device configurations, read Providing Resources. To
learn more about best practices and designing robust, production-quality apps,
see Guide to App Architecture.

Итог

Развитие данной технологии имеет огромный потенциал. На карте стоит развенчание мифа о медлительности и нестабильности Android, что не только порадует владельцев устройств под ее управлением, но и ликвидирует наиболее серьезный аргумент в спорах со стороны приверженцев iOS.

На данный момент представители компании Google не сообщают о сроках окончательного внедрения и замены Dalvik на ART. Хочется верить, что это произойдет уже очень скоро.

Здравствуйте! Если вы не понимаете, что изменится для пользователя при изменении среды выполнения из Dalvik в ART, то этот пост вам будет интересен. Прежде чем говорить о новой среде, давайте поговорим о всем известной среде Dalvik Определение Dalvik Virtual Machine — виртуальная машина основанная на регистрах, разработанная Дэном Борнштейном, как часть мобильной платформы Android. Для чего нужна виртуальная машина Dalvik? Dalvik…

Здравствуйте!
Если вы не понимаете, что изменится для пользователя при изменении среды выполнения из Dalvik в ART, то этот пост вам будет интересен.
Прежде чем говорить о новой среде, давайте поговорим о всем известной среде Dalvik

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (Пока оценок нет)
Загрузка...
Понравилась статья? Поделиться с друзьями:
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!:

Adblock
detector