Xamarin vs android studio 2021

Cross-platform mobile apps development in 2021: Xamarin vs React Native vs Flutter vs Kotlin Multiplatform

Let’s make things clear from the beginning. There is no way in which cross-platform mobile apps can match native mobile apps in performance, user, and developer experience. And they won’t ever be able to do it. Everything else is just marketing 😉

Native mobile apps are developed separately for Android (Kotlin) and iOS (Swift). Ecosystems are supported by Google and Apple correspondingly, so developers get the newest, the most stable, the most convenient tools (Android Studio, XCode), SDKs, and libraries for work.

There are only two issues about native mobile development: cost and consistency. If there is a problem, there must be a solution. Considerable market for cross-platform frameworks already exists. But let’s see if they solve those two problems without creating new ones.

Important players

There are dozens of cross-platform frameworks, but not all of them are born equal. Honestly, there are just a few tools, which is worthy to consider at the moment. You will find the four most promising in the table below.

I can’t recommend PWA (Progressive Web Apps) and other web-based frameworks, because the resulting user and developer experience is rather frustrating, even though the cost is low.

Xamarin

Founded in 2011, and acquired by Microsoft in 2016, the company has developed an open-source C#-based framework, which allows the creation of mobile apps for iOS, Android, and Windows Phone from a single codebase (UI and business-logic) using C# and XAML.

Xamarin is considered to be a failed attempt by Microsoft to enter the mobile devices space, largely dominated by Google and Apple. Since the discontinuation of Windows Phone in 2015, Xamarin and its ecosystem are on the decline as well.

Most Android and iOS SDKs are wrapped and accessible from C# client code. In the case of missing functionality, native libraries and native code can be integrated with Xamarin applications, but it requires Android / iOS skills from the developer, which is rarely the case.

Xamarin is an obvious choice for C# developers, who want to try mobile apps development. Due to the limited set of dedicated Xamarin libraries, which are often outdated, Xamarin apps have often an unsatisfactory experience for clients, developers, and users in long term projects.

Written code can’t be easily migrated to native mobile apps or other cross-platform frameworks. So once chosen, Xamarin must be used for all features in the project.

React Native

Born during the internal hackathon at Facebook in 2015, React Native brings the React approach to the mobile world. Single codebase (UI and business-logic) is written in JavaScript and then compiled into native apps.

Technology is actively supported by Facebook and the open-source community. Android and iOS SDKs are wrapped and exposed to JavaScript pretty much the same way as with Xamarin. But due to the popularity, there are many more actively supported 3rd party libraries.

When some missing functionality occurs, developers need to implement special native modules in Kotlin / Swift and integrate them into the React Native app. It requires Android / iOS skills, which is rarely the case because technology is mainly targeted to web developers.

Читайте также:  Как настроить экран смартфона android

So a perfect React Native developer needs to know JavaScript + React Native SDK, Kotlin + Android SDK, Swift + iOS SDK, which is 3x of knowledge compared to common native mobile developers. Hence lack of good developers and elevated rates (fortunately not 3x).

Once you decide to use React Native for your project there is no easy way out. Migration to other cross-platform frameworks or native mobile apps will require a full rewrite.

Flutter

The fastest-growing cross-platform framework unveiled by Google in 2017. Due to the size of the company and internal teams’ conflicts, Google supports 2 technologies for mobile development at the same time — native Android with Kotlin, and cross-platform Flutter with Dart.

One of the main pain points of cross-platform developers with Xamarin and React Native was struggling with limited support for customization of native UI components, which are used internally in both frameworks.

Flutter solved this issue with its own UI engine and components, so they are rendered by Flutter himself and look exactly the same way on all devices. Another side of this approach is that UI is different from any native application, which may not be the desired behavior in some cases.

Dart language was developed by Google well before the Flutter framework but struggled to find solid adoption. Hence all developers are equal with Flutter and need to learn it from scratch. The ecosystem isn’t yet as mature as React Native’s one but is quickly growing.

Native libraries and code can be integrated with Flutter applications, so some iOS / Android skills are needed as well. Again the same 3-language problem, requiring developers to be good at 3 technologies at the same time.

Since Flutter uses Dart, and the framework is written almost from scratch, developers will have a hard time migrating Flutter projects to other cross-platform frameworks or native applications. Literally, they will need to rewrite everything from zero.

Kotlin Multiplatform

Wait, isn’t Kotlin a language used for native Android development? Yes, but there is an interesting feature of Kotlin called Kotlin Multiplatform, which allows some parts of the Android application to be reused on iOS, Web, Desktop, and pretty much anywhere.

So Kotlin Multiplatform isn’t a cross-platform framework, but rather an optional code-sharing tool, which can be used in both, apps started from scratch and existing native applications. It gives developers unprecedented flexibility in what to share, and what not to share.

It’s recommended to share the business logic of mobile applications, including networking, database, business, and presentation logic, which is not platform-specific and can be easily reused. In contrast, it’s not recommended to share UI components, which are much dependent on native platforms’ capabilities.

The target audience of Kotlin Multiplatform is native mobile developers, who already use Kotlin on Android and Swift on iOS. In other words, these are developers with a deep understanding of native mobile SDKs, which need to learn only one new language (Swift or Kotlin).

Thus Kotlin Multiplatform can be progressively learned in a few weeks. Too good to be true? Well, there are some drawbacks mainly related to the fact that Kotlin Multiplatform went Alpha just a few months ago.

While Android developers’ experience is 99% the same for Kotlin Multiplatform, iOS developers may struggle at first to grasp this new approach. But the learning curve is quite quick as well.

Читайте также:  X android received millis

Even though needed native functionality can be effortlessly integrated with shared code through expect / actual mechanism, there are many libraries officially supported by JetBrains (creators of Kotlin and Kotlin Multiplatform) and the community.

There are also some rough corners in interoperability between Kotlin and Swift (see “Kotlin Multiplatform: ready, steady, …” for more details), but once you are aware of those problems, you can easily avoid them.

From my own experience, Kotlin Multiplatform allows saving about 30% of development time, which is not far from other players in space like React Native, Flutter, or Xamarin.

Bottom line

If you are starting your project from scratch, and going to ship POC (Proof of Concept), or MVP (Minimum Viable Product) in the shortest term possible, consider using Flutter or React Native. But be ready to face the technology limitations, and always be a few steps behind the market, or rewrite mobile applications once again using native technologies.

If you have existing native mobile applications or want to get the most from native mobile platforms, consider using Kotlin Multiplatform, which requires almost zero effort from your Android developers, but can save a lot of time on the iOS side. In the worst case, you simply reimplement the failed shared part in Swift, no obligations 😉

Talking about the time & cost of mobile apps development, there is no official statistic about any of the cross-platform frameworks. But if we consider efforts needed to develop 2 separate native mobile applications as 100%, any of mentioned in this article solutions can save about 30% of your team bandwidth depending on complexity of your project.

Источник

Сравнение производительности Xamarin (monodroid) и Java (DalvikVM) на Android устройствах


Добрый день. Многие интересуются насколько сильно отличается производительность Xamarin на Android или iOS. Вопрос с iOS я пока оставлю открытым, а вот все вопросы по производительности monodroid предлагаю закрыть раз и навсегда.

Зачастую эти вопросы вызваны из-за неправильного понимания как устроен monodroid, мне например задавали вопросы типа «А Xamarin потом пересобирается под JVM?». Это конечно же не так. Важно понимать, что Xamarin выполняется на том же уровне Android где работает виртуальная машина Android Dalvik. Поэтому при сравнении производительности мы на деле имеем сравнение эффективности работы двух виртуальных машин: Mono VM и Dalvik VM.

Методика проверки

Для проверки производительности необходим реализованный на Java и общепризнанный метод, который необходимо будет реализовать на C#. Я решил использовать известный тест производительности LINPACK в первую очередь потому что его исходный код открыт и легко будет реализовать C# версию, а во-вторую — есть уже готовая Android версия LINPACK for Android написанная на Java.

Тест производительности LINPACK это метод оценки производительности путем оценки скорости выполнения операций с плавающей точкой вычислительной системы. Бенчмарк создан Джеком Донгарра (Jack Dongarra) и измеряет как быстро компьютер ищет решение плотной СЛАУ Ax = B размерностью N x N методом LU-декомпозиции. Решение получено методом Гаусса с выделением главного элемента (описание), при котором выполняется 2/3*N 3 + 2*N 2 операций с плавающей точкой. Результат определяется в Floating-point Operations Per Second(MFLOP / s, чаще просто FLOPS). Сам тест производительности был описан в документации к фортрановской библиотеке линейных вычислений LINPACK и с тех пор его вариации используются, например, для составления рейтинга TOP500 суперкомпьютеров.

Реализация

Несмотря на довольно простую задачу я решил реализовывать ее согласно выработанному мною гайдлайну на кроссплатформенную разработку.

Читайте также:  Прошивка для самсунг а5 2016 андроид

На первом шаге строим кроссплатформенное решение:

Потом согласно шаблону проектирования MVP создаем Presenter и View

Пишем тесты и реализуем Presenter через тест. Для этого я использую NUnit и NSubstitute. Описывать NUnit особого смысла нету, на мой взгляд более удобного фреймворка для тестирования просто нету. NSubstitute это крайне удобный фреймворк для создания заглушек на основании интерфейсов. Фреймворки устанавливаются через NuGet.

В нашем случае сначала создаем Setup метод

И выполняем простой тест, естественно асинхронно

Сторонним ПО я выяснил что производительность моего ПК — около 130 MFLOPS/s, так что его и впишем в ожидаемые значения, добавив погрешность.

Внутри метода у меня создание асинхронной Task и заполнение View. Все просто и понятно

Программа фактически реализована, ни строчки платформозависимого кода пока написано не было. Теперь создаем Android проект:

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

Теперь остается только скомпилировать релиз, подписать его приложенным к студии мастером и установить на устройства с помощью консольной утилиты adb.exe

Недавно я приметил, что скорость выполнения кода зависит не только от Debug/Release но и от подключения устройства по USB. Происходит это из-за того что при подключенном телефоне в режиме разработки Android гонит огромные объемы отладочной информации на компьютер, что может повлиять на скорость выполнения операций (а может и не повлиять), особенно если есть конструкции логирования типа Trace. Поэтому отключаем устройства и запускаем тесты.

Результат

У меня два тестовых устройства, HTC Desire с Android 2.3 (Qualcomm QSD8250, 1000 МГц, 512 ОЗУ) и Fly IQ443 с Android 4.0.4 (MediaTek MT6577, 1000 МГц, 512 ОЗУ)

Вот их результаты:
HTC Desire:

Fly IQ443:

И красивые графики

Вывод

Результаты теста показывают что работа Mono на Android как минимум сравнима, а иногда и превосходит производительность Dalvik, но в целом они примерно равны. Второй столбец некорректен, т.к. Mono самостоятельно распараллелил тест на два ядра без каких либо действий с моей стороны, полагаю где-то на уровне Task’ов, в то время как для Linpack for Android необходимо явно выбрать мультипоточный тест.

Кстати говоря, этот проект показывает различия в размерах для релизовых сборок. Java версия теста весит всего лишь 280Кб, когда Monodroid версия весит почти 2.3 МБ на один тип процессора (armeabi и armeabi-v7), т.е. в сумме 4.6 МБ, что впрочем в условиях современных сетей не кажется мне особо критичным. Если такой размер apk кажется вам неприемлемым можно отдельно собрать и распространять пакеты для armeabi и armeabi-v7, благо Google Play позволяет загружать разные apk для разных платфом.

Исходный код приложения находится здесь

P.S. Мне бы хотелось собрать статистику по устройствам. Так что если у кого есть Android и 10 минут свободного времени буду очень благодарен если вы измерите производительность вашего устройства с помощью LINPACK for Android и вновь созданной MonoLINPACK и запишите результат сюда (если у вас многоядерный процессор выбирайте сразу Run Multiple Thread в LINPACK for Android)

P.P.S. Аналогичный тест для iOS будет

UPD1 По текущим тестам видно что Mono и Task по умолчанию не использует все ядра на 4-ядерных процессорах. Поэтому результаты между Linpack for Android и MonoLinpack на таких устройствах сильно различаются. В ближайшее время MonoLINPACK будет модифицирован с использование TPL.

Источник

Оцените статью