2 июня 2023, 1:21

Performance Bottlenecks Hiding on the Client Side

As an iOS engineer, for the most time in my career, I have been “transforming JSONs into beautiful UI”. Compared to backend development, handling large amounts of data and doing performance optimizations are not a typical part of our work. Of course, from time to time, performance does matter — especially to make the UI smooth, but the techniques are often different — such as reusing views or offloading expensive work from the main thread. Additionally, if we want the client to be thin, most of the heavy job is delegated to the server, for example, content ranking, search, filtering and so on.

However, sometimes you still have to perform some expensive operations on the client side — for example, because for privacy reasons you don’t want some local data to leave the device. It’s easy to accidentally make those parts of code extremely inefficient — especially if you haven’t built this muscle of quickly spotting potential complexity issues yet. Algorithms and data structures do matter — this is something I only truly realized only several years into my mobile career, and I still see this thing to be often overlooked in the industry. Of course, early optimization is not needed and may even do harm (see premature optimization), but even basic calculations can become performance bottlenecks that severely harm user experience.

There is only one way to solve it — embrace the basics — which means using appropriate algorithms and data structures for the task at hand. One real example that I always recall is a thing I built for one of my projects many years ago. For an invitation flow, I had to implement a contact merge feature where the data would come from three different sources — backend, social account and local iPhone address book. We wanted to combine contacts from these sources into one if they had any overlapping channels (phone numbers or emails). The result would be an array of contacts with all their channels, so there would be no duplicate channels for two different contacts.

At first, my naive approach was just to go one by one and see if in the remainder of the list any contact has overlapping channels with the current one, merge them if yes, repeat. This was needed because, for example, the last channel in the list could have two channels — one that would overlap with the current one, and the second one that could have appeared in the previous contacts which would mean having to go through the list again.

I implemented this, and it worked pretty reliably, here is the pseudocode:

func slowReliableSmartMerge(contacts: [Contact]) -> [Contact]  {
    var mergedContacts = contacts
    var results = [Contact]()
    var merged = true

    while merged {
        merged = false
        results.removeAll()

        while !mergedContacts.isEmpty {
            var commonContact = mergedContacts.first!
            let restContacts = mergedContacts.dropFirst()

            mergedContacts.removeAll()

            for contact in restContacts {
                if contact.hasNoOverlappingChannels(with: commonContact) {
                    mergedContacts.append(contact)
                } else {
                    merged = true
                    commonContact = Contact.mergedContactFrom(contact: commonContact, otherContact: contact)
                }
            }
            results.append(commonContact)
        }

        mergedContacts = results
    }

    return mergedContacts
}

An experienced engineer would quickly spot the issue here, but plese bear with me for a minute. I tested this on my device which had roughly 150 local contacts, 100 friends on social media, and a couple dozen users from the server. It would finish in just a couple of seconds after showing a spinner — “not a huge deal” I thought and moved on to the next feature. Test devices had much fewer contacts, so it worked instantly there. Then a couple of weeks later we started getting some reports from the users that this spinner can take a minute or even longer. Suddenly I realized that the issue was related to complexity, and then I figured that the approach I had taken could actually hit the O(n^2) complexity — similar to the bubble sort.

I quickly discussed that with another engineer on a whiteboard, and we came up with hashmaps to optimize this significantly:

func smartMerge(contacts: [Contact]) -> [Contact] {
    var channelToContact = [String: Contact]()
    var contactToChannels = [Contact: Set<String>]()

    for contact in contacts {
        var mergedContact = contact

        for channel in contact.allChannels {
            if let matchingContact = channelToContact[channel] {
                if mergedContact !== matchingContact {
                    let mergedMatchingContact = Contact.mergedContactFrom(contact: matchingContact, otherContact: mergedContact)
                    contactToChannels[mergedMatchingContact] = (contactToChannels[mergedContact] ?? []).union((contactToChannels[mergedMatchingContact] ?? []))

                    if let channels = contactToChannels[mergedContact] {
                        for c in channels {
                            channelToContact[c] = mergedMatchingContact
                        }
                    }

                    contactToChannels[mergedContact] = nil

                    mergedContact = mergedMatchingContact
                }
            } else {
                channelToContact[channel] = mergedContact

                if contactToChannels[mergedContact] != nil {
                    contactToChannels[mergedContact]!.insert(channel)
                } else {
                    contactToChannels[mergedContact] = [channel]
                }
            }
        }
    }

    return contactToChannels.keys
}

The eventual complexity was linear, the spinner would just flicker for a split second, and the tests were luckily green.

Since then, I’ve always been much more alert when it comes to doing some computation on the client side that potentially can have a variable-sized input. This all seems to be very obvious to me now, but back in the day this didn’t look too important to me. I think having a proper understanding of the complexity that comes with various algorithms and data structures can make you a much better software engineer which will lead to better products you build. After all, this is how the big tech companies hire — they value coding skills more than knowledge of certain frameworks.

These days, it’s also important for new folks who switch to software engineering from other areas — they often start their career with simple projects that involve UI work or simply connecting the stuff that’s built on top of well-known frameworks. I’d encourage them to also master the core things like algorithms in order to excel at this job.

Поделиться
58 комментариев
chaisax

[url=https://zavaristika.ru/catalog/puer]купить прессованный пуэр[/url] или [url=https://zavaristika.ru/catalog/puer]где купить пуэр[/url]

https://zavaristika.ru/catalog/shu-puer-chernyj

Интернет-магазин «4Mac»

Интернет-магазин «4Mac» — это качественные и недорогие запчасти для телефонов,
планшетов и ноутбуков с доставкой по Москве и всей России.
Каталог, цены. Телефон: +7 495 255 73 79

Stevenheafe

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

Создавайте интернет-магазины с контентом и товарами вашего поставщика. Создание и наполнение интернет-магазинов и сайтов-каталогов. Автоматический перенос каталога товаров вашего поставщика в ваш интернет-магазин.
(Я работаю с сайтами любой сложности, с защитой от копирования и captcha) Извлечение данных с сайтов, защищенных от копирования, решение captcha и recaptcha.
И обработка данных в формате CSV, Excel.

Большой опыт в разработке и извлечении данных с веб-сайтов.
Автоматический сбор данных с веб-сайтов компаний, телефонных номеров, электронных писем и каталогов продукции.
Также большой опыт в публикации контента на веб-сайтах и в интернет-магазинах.

Я работаю с программным обеспечением для веб-автоматизации и синтаксического анализа
ZennoPoster, BrowserAutomationStudio, ZennoDroid
Я занимаюсь веб-очисткой, очисткой данных, сбором данных, извлечением данных, обходом веб-страниц. Я занимаюсь разработкой веб-ботов. Я консультант по очистке веб-страниц и инженер по обработке данных. Разработка и автоматизация пользовательских ботов

Contacts:
https://www.linkedin.com/in/anatoliy-barsukov-52194bb4/
Tel/Viber/WhatsApp:
+79818525114
Skype anato27

maryeyyu

Прогон сайта лиц.Заказать <a href=https://seoprofisional.ru/bazy/progon-xrumer>прогон Хрумером </a> и ГСА по Траст базам с гарантией. Беру за основу для продвижения Ваши ключевые слова и текст.
Заказать Прогон Хрумером и ГСА можно в телеграмм логин @pokras777 здесь наша группа в телеграмм https://t.me/+EYh48YzqWf00OTYy или в скайпе pokras7777

BrianZet

Всем привет, представляю для вас музыкальную коллекцию всех стилей музыки,
у нас найдется любой стиль музыки для вас, сервер вмещает в себе 270TB mp3/flac альбомов,
заходите пишите ответим на любые вапросы. https://sceneflac.blogspot.com

BruceGaw

nd_user — Nice Article! Pavel Shadrin read this
Отличный подарок для любимой —
[url=https://pornopda.xyz/shop/seks_igrushki/vibratori/]вибратор lovense lush купить[/url]
Новый Lovense Lush вибратор уже доступен для покупки в нашем магазине.

[url=https://funnyenglish.es/funny-english-escuela-ingles]фаллоимитатор купить с доставкой[/url]
[url=http://vanilleblau.at/vanilleblau/comment-page-1#comment-200450]гибкий фаллоимитатор[/url]
[url=http://arenasoccer.mex.tl/?gb=1#top]купить вибратор vipsex[/url]
[url=http://keylamusik.mex.tl/?gb=1#top]купить большой фаллоимитатор[/url]
[url=https://www.indianswaad.dk/2019/03/28/hej-verden/#comment-148675]женщины большие фаллоимитаторы[/url]
d0474b8

Matthewadvax

[url=https://prokat-59.ru/]Покупка инструмента[/url] может быть дорогой, особенно если вам нужно использовать его только на короткое время. Аренда инструмента позволяет сэкономить деньги, поскольку вы платите только за время использования.

прокат инструмента в Перми [url=https://prokat-59.ru]прокат инструмента в Перми[/url].

MarvinRag

Умная наклейка с номером поможет открывать подъездный домофон любым предметом который часто бывает так сказать «под рукой».

Syaak_bdot

InMotion Hosting: InMotion Hosting offers fast and reliable hosting services with excellent customer support. They provide a variety of hosting options, including business hosting, VPS hosting, and dedicated servers.
HostGator: HostGator is known for its affordable plans and reliable performance. They offer unlimited storage and bandwidth, a variety of hosting options, and excellent customer support. [url=http://webward.pw/]http://webward.pw/[/url].

OlpTwive

Hi!
Earn every MINUTE without limit of 100, 200, 500, 1000 and whiter Dollars USA, there are NO limits!

We have been trusted by millions of people around the world since 2014!
The most convenient platform for online trading and investment 2023!
*Awarded by FxDailyInfo, a reputable international resource!
*World Business Outlook Award!
The most reliable financial broker 2023!

+ Instant withdrawal!
+ Demo account +10 000D!
+ Free Signals!
+ Free training!
+ *PROMO-CODE*: OLYMPOLYMP
*From $50 +30% to deposit!

WARNING! If registration is closed for your country, you need to enable VPN and choose a country from which registration is not prohibited, for example (Singapore).
After registration you can disable VPN and start earning, it is allowed!

Sign up, and earn unlimited earnings every 60 seconds!
The promo code is valid on these links only!

DOWNLOAD IOS APP (App Store)
https://app.appsflyer.com/id1053416106?pid=affiliate&c=101773&af_siteid=101773&af_sub2=App-Store&af_sub1=XR

DOWNLOAD ANDROID APP (Google Play)
https://app.appsflyer.com/com.ticno.olymptrade?pid=affiliate&c=101773&af_siteid=101773&af_sub2=Google-Play&af_sub1=XR

WEB VERSION
https://trkmad.com/101773/

Matthewadvax

В случае возникновения проблем или вопросов по использованию инструмента, вы можете обратиться за помощью к специалистам компании, предоставляющей [url=https://prokat-59.ru/]на Прокат инструмент[/url]. Они могут предоставить вам необходимую техническую поддержку и помочь решить любые проблемы.

аренда инструмента [url=http://www.prokat-59.ru]прокат инструмента в Перми[/url].

HenryPleak

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

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

Заказать сео оптимизацию и продвижение вашего проэкта можно у нас в телеграмм @pokras777 либо в скайпе pokras7777

так же присаединяйтесь к нам в группу ====>>> https://t.me/bazixrumer ответим на все интересующие вас вопросы
так же можно <a href=https://seoprofisional.ru/bazy/progon-xrumer>заказать прогон xrumer</a> отдельно цена расчитавается индивидуально

JosephNeows

<a href=https://kwork.ru/links/1017228/progon-khrumerom>прогон по профилям</a>

kofsax

[url=https://mtw.ru/colocation]услуги colocation[/url] или [url=https://mtw.ru/]дата центр аренда места[/url]

https://mtw.ru/registraciyadomenov аренда места под сервер в цод

Oliversbo

Это действительно классный и полезный фрагмент информации. Я удовлетворен что вы поделились с нами этой полезной информацией. Пожалуйста, держите нас в курсе вот так. Спасибо за то, что поделились.
Предлагаю также ознакомиться с моей страничкой о продвижении сайтов
в интернете и привлечению посетителей:
https://baoly.ru/19
https://kwork.ru/links/20814607/sozdam-polnotsennuyu-pbn-set-saytov
https://www.chimatamusic.net/db/viewtopic.php?p=2217325&highlight=

@qa

sokeEndeask

Логистическая компания — ООО «Лазурит» оказывает полный комплекс внешнеэкономических услуг в Юго-Восточной Азии

<a href=https://lazuritllc.ru>Выкуп товаров в Юго-Восточной Азии</a>
<a href=https://lazuritllc.ru>Международная перевозка грузов</a>
<a href=https://lazuritllc.ru>Таможенное оформление товаров</a>
<a href=https://lazuritllc.ru>Сертификация товаров и автомобилей</a>

Мы предоставляем нашим клиентам решающее конкурентное преимущество.

Krypterixx

Программа для автоматического заработка на вашем компьютере в фоновом режиме.
Работа программы осуществляется путем майнинга криптовалют, никаких настроек делать не нужно, система сама определяет наиболее выгодную на текущий день криптовалюту для майнинга и работает с ней.
Чем мощнее компьютер, тем выше показатели заработка. Программу можно устанавливать на нескольких компьютерах, например дома и на работе — Чем больше компьютеров — тем больше заработок. Вся Работа системы происходит в фоновом режиме и не мешает работе на ПК.
Для определения доходности программу желательно тестировать день-два, так как показатели дохода «плавают» и могут отличаться в разные моменты (из-за роста и падения цен на криптовалюты).
Подробное описание и скачивание программы: https://u.to/ax7hHw

Oliverzwi

Это на самом деле замечательный и полезный фрагмент информации. я рад что вы поделились с нами этой полезной информацией. Пожалуйста, оставайтесь нас информированными вот так. Спасибо за то, что поделились.
Предлагаю также ознакомиться с моей страничкой о маркетинге в интернете и повышении трафика:
https://baoly.ru/kgnr
https://baoly.ru/24
https://baoly.ru/463676478

@qa

Coreyfut

de Nexo token verhandelbaar op allerlei exchanges zoals Huobi, Localcoinswap, Binance Dex, HitBTC en een paar andere
https://localcoinswap.net

Coreyfut

don’t know how and where to buy bitcoin, we recommend localcoinswap.net
https://localcoinswap.net

Coreyfut

Localcoinswap (renomovana platforma P2P) je renomovana burza P2P, kde muzete nakupovat a prodavat bitcoiny
https://localcoinswap.net

Coreyfut

using P2P (Peer to peer) exchanges like Bisq, Onlybestoffers.trade Paxful, LocalSwap and LocalBitcoins
https://localcoinswap.net

Coreyfut

de Nexo token verhandelbaar op allerlei exchanges zoals Huobi, Localcoinswap, Binance Dex, HitBTC en een paar andere
https://localcoinswap.net

Coreyfut

LocalCoinSwap seems to be heavily inspired by LocalBitcoins
https://localcoinswap.net

Coreyfut

LocalCoinSwap seems to be heavily inspired by LocalBitcoins
https://localcoinswap.net

Coreyfut

using P2P (Peer to peer) exchanges like Bisq, Onlybestoffers.trade Paxful, LocalSwap and LocalBitcoins
https://localcoinswap.net

Coreyfut

Localcoinswap (reputable P2P platform) is a reputable P2P exchange where you can buy and sell bitcoins
https://localcoinswap.net

Coreyfut

кроме Binance P2P есть ещё LocalBitcoins, Bitpapa, LocalCoinSwap, Bitzlato, LocalCryptos
https://localcoinswap.net

Coreyfut

using P2P (Peer to peer) exchanges like Bisq, Onlybestoffers.trade Paxful, LocalSwap and LocalBitcoins
https://localcoinswap.net

Coreyfut

de Nexo token verhandelbaar op allerlei exchanges zoals Huobi, Localcoinswap, Binance Dex, HitBTC en een paar andere
https://localcoinswap.net

Coreyfut

кроме Binance P2P есть ещё LocalBitcoins, Bitpapa, LocalCoinSwap, Bitzlato, LocalCryptos
https://localcoinswap.net

Coreyfut

Localcoinswap (renomovana platforma P2P) je renomovana burza P2P, kde muzete nakupovat a prodavat bitcoiny
https://localcoinswap.net

Coreyfut

de Nexo token verhandelbaar op allerlei exchanges zoals Huobi, Localcoinswap, Binance Dex, HitBTC en een paar andere
https://localcoinswap.net

Coreyfut

LocalCoinSwap is another peer-to-peer (P2P) cryptocurrency exchange that allows users to trade bitcoins
https://localcoinswap.net

Coreyfut

Localcoinswap (renomovana platforma P2P) je renomovana burza P2P, kde muzete nakupovat a prodavat bitcoiny
https://localcoinswap.net

Coreyfut

кроме Binance P2P есть ещё LocalBitcoins, Bitpapa, LocalCoinSwap, Bitzlato, LocalCryptos
https://localcoinswap.net

Coreyfut

por lo que el sitio ideal en este caso seria Localbitcoins.net
https://localcoinswap.net

Coreyfut

Compra y vende bitcoin en LocalCoinSwap
https://localcoinswap.net

Coreyfut

using P2P (Peer to peer) exchanges like Bisq, Onlybestoffers.trade Paxful, LocalSwap and LocalBitcoins
https://localcoinswap.net

Coreyfut

de Nexo token verhandelbaar op allerlei exchanges zoals Huobi, Localcoinswap, Binance Dex, HitBTC en een paar andere
https://localcoinswap.net

Coreyfut

de Nexo token verhandelbaar op allerlei exchanges zoals Huobi, Localcoinswap, Binance Dex, HitBTC en een paar andere
https://localcoinswap.net

Coreyfut

LocalCoinSwap is another peer-to-peer (P2P) cryptocurrency exchange that allows users to trade bitcoins
https://localcoinswap.net

Coreyfut

Localcoinswap (renomovana platforma P2P) je renomovana burza P2P, kde muzete nakupovat a prodavat bitcoiny
https://localcoinswap.net

Coreyfut

Compra y vende bitcoin en LocalCoinSwap
https://localcoinswap.net

Coreyfut

кроме Binance P2P есть ещё LocalBitcoins, Bitpapa, LocalCoinSwap, Bitzlato, LocalCryptos
https://localcoinswap.net

Coreyfut

using P2P (Peer to peer) exchanges like Bisq, Onlybestoffers.trade Paxful, LocalSwap and LocalBitcoins
https://localcoinswap.net

Coreyfut

don’t know how and where to buy bitcoin, we recommend localcoinswap.net
https://localcoinswap.net

Coreyfut

LocalCoinSwap seems to be heavily inspired by LocalBitcoins
https://localcoinswap.net

Coreyfut

don’t know how and where to buy bitcoin, we recommend localcoinswap.net
https://localcoinswap.net

Coreyfut

LocalCoinSwap is another peer-to-peer (P2P) cryptocurrency exchange that allows users to trade bitcoins
https://localcoinswap.net

Coreyfut

por lo que el sitio ideal en este caso seria Localbitcoins.net
https://localcoinswap.net

Coreyfut

LocalCoinSwap seems to be heavily inspired by LocalBitcoins
https://localcoinswap.net

Coreyfut

LocalCoinSwap seems to be heavily inspired by LocalBitcoins
https://localcoinswap.net

Coreyfut

LocalCoinSwap is another peer-to-peer (P2P) cryptocurrency exchange that allows users to trade bitcoins
https://localcoinswap.net

Coreyfut

Localcoinswap (reputable P2P platform) is a reputable P2P exchange where you can buy and sell bitcoins
https://localcoinswap.net

HarryElard

Compra y vende bitcoin en LocalCoinSwap
https://localcoinswap.net

MarysOi5952

XEvil 6.0 автоматически решает большинство типов капч,
В том числе такой тип капчи: ReCaptcha-2, ReCaptcha-3, Hotmail, Google, SolveMedia, Rambler, Yandex, VKontakte, Odnoklassniki, Mamba, Mail.ru, WoT, +12000
+ hCaptcha поддерживается в новом XEvil 6.0!

1.) Быстро, легко, точно
XEvil — самый быстрый убийца капчи в мире. У него нет ограничений на решение, нет ограничений на количество потоков
вы можете решить даже 1.000.000.000 капч в день, и это будет стоить 0 (НОЛЬ) долларов США! Просто купите лицензию за 59 долларов США и все!

2.) Поддержка нескольких API-интерфейсов
XEvil поддерживает более 6 различных всемирно известных API: 2captcha.com, anti-captchas.com (antigate), rucaptcha.com, DeathByCaptcha, etc.
просто отправьте свою капчу через HTTP-запрос, как вы можете отправить в любой из этих сервисов — и XEvil разгадает вашу капчу!
Итак, XEvil совместим с сотнями приложений для SEO / SMM / восстановления паролей / парсинга /публикации / кликов / криптовалюты / и т. д.

3.) Полезная поддержка и руководства
После покупки вы получили доступ к частному форуму технической поддержки, Wiki, онлайн-поддержке Skype/Telegram
Разработчики обучат XEvil вашему типу captcha бесплатно и очень быстро — просто пришлите им примеры

4.) Как получить бесплатную пробную версию полной версии XEvil?

  • Попробуйте поискать в Google «Home of XEvil»
  • вы найдете IP-адреса с открытым портом 80 пользователей XEvil (нажмите на любой IP-адрес, чтобы убедиться)
  • попробуйте отправить свою капчу через 2captcha API на один из этих IP-адресов
  • если вы получили ошибку с НЕПРАВИЛЬНЫМ КЛЮЧОМ, просто введите другой IP-адрес
  • наслаждайтесь! :)
  • (это не работает для hCaptcha!)

ВНИМАНИЕ: Бесплатная ДЕМО-версия XEvil не поддерживает reCAPTCHA, hCaptcha и большинство других типов captcha!

http://xrumersale.site/

Ваш комментарий
адрес не будет опубликован

ХТМЛ не работает

Ctrl + Enter
Популярное