...

What We Think

Blog

Keep up with the latest in technological advancements and business strategies, with thought leadership articles contributed by our staff.
TECH

December 6, 2023

Unleashing the Power of Smart Pointers in C++

In the dynamic landscape of C++ programming, mastering memory management is paramount for creating robust and reliable code. A key ally in this endeavor is the smart pointer, a powerful tool designed to streamline memory handling and eliminate common pitfalls. In this post, we will delve into the world of smart pointers and explore their usage through illustrative code samples.

1. Understanding Smart Pointers

Smart pointers are objects in C++ that mimic the behavior of pointers while adding features to automate memory management. Unlike raw pointers, smart pointers automatically handle memory allocation and deallocation, reducing the likelihood of memory leaks and enhancing code readability.

Types of Smart Pointers:

C++ offers three main types of smart pointers:

1.1 std::unique_ptr

  • Represents exclusive ownership of an allocated resource.
  • Ensures that only one unique_ptr points to a specific memory location.
  • Automatically deallocates memory when the unique_ptr goes out of scope.

Output:

1.2 std::shared_ptr

  • Allows multiple smart pointers to share ownership of the same resource.
  • Keeps track of the number of shared_ptrs pointing to a resource.
  • Deallocates memory only when the last shared_ptr is destroyed.

Output:

1.3 std::weak_ptr

  • A weak_ptr is used in conjunction with shared_ptr to break circular references.
  • It provides a non-owning, weak reference to an object controlled by a shared_ptr.
  • Weak pointers do not affect the reference count of the shared_ptr.

Output:

2. Differences among the pointers

Before making decisions on which type of pointer to use in your project, let's collectively examine the distinctions for each type of pointer:

  std::unique_ptr std::shared_ptr std::weak_ptr
Ownership Represents exclusive ownership of a dynamically allocated object. It ensures that only one unique_ptr can own the object at a given time. When the unique_ptr is destroyed, it deletes the associated object. Represents shared ownership of a dynamically allocated object. It keeps a reference count, and multiple shared_ptr instances can share ownership of the same object. The object is only deleted when the last shared_ptr owning it is destroyed.  It is used in conjunction with shared_ptr and does not affect the reference count. It provides a non-owning "weak" reference to an object held by a shared_ptr. It is useful to break circular references in situations where shared_ptr is used.
Copying and Assignment Cannot be copied. It can only be moved, indicating a transfer of ownership. Can be copied, and each copy shares ownership of the object. The reference count is increased with each copy. Can be copied, but it does not affect the reference count. It is used to observe the state of a shared_ptr without affecting its ownership.
Performance and Overhead Typically has lower overhead compared to shared_ptr because it does not maintain a reference count. Has a higher overhead due to maintaining a reference count to manage shared ownership. Introduces minimal overhead compared to shared_ptr.
Use Cases Use when you have exclusive ownership and want to transfer ownership or use move semantics. It is a good choice for resource management. Use when multiple owners need to share ownership of an object. It provides automatic memory management and helps avoid memory leaks. Use when you need to break circular references in situations where shared_ptr is used. It is often used in combination with shared_ptr to prevent strong reference cycles.
Thread Safety Not designed for sharing ownership across multiple threads. Provides thread-safe reference counting, making it suitable for shared ownership across multiple threads. Provides a non-owning reference and does not affect the reference count atomically. It should be used with caution in a multi-threaded environment.

In summary, the choice between unique_ptr, shared_ptr, and weak_ptr depends on the ownership requirements and the desired behavior of your program. Each smart pointer has its own strengths and use cases.

3. Benefits of Smart Pointers

Automatic Memory Management:

Smart pointers automate memory allocation and deallocation, reducing the risk of memory leaks.

Enhanced Safety:

Helps prevent common pitfalls like dangling pointers and null pointer dereferencing.

Improved Code Readability:

Leads to cleaner and more readable code, allowing developers to focus on program logic.

4. Conclusion

Smart pointers have become indispensable in modern C++ programming, offering a safer and more convenient approach to memory management. By incorporating unique_ptr, shared_ptr, and weak_ptr into your codebase, you can significantly improve the robustness and maintainability of your software. As you embrace smart pointers in your C++ journey, you'll discover a more efficient and reliable path to creating high-quality applications.

 

[Reference Source]

  • https://learn.microsoft.com/en-us/cpp/cpp/smart-pointers-modern-cpp?view=msvc-170
View More
TECH

December 5, 2023

Why the Android so popular

We are in the 4.0 era and smartphones are an indispensable device in daily life. Smartphones today are present in every area of human life. They come from many different brands, but if classified by operating system, there are two popular platforms: Android and iOS.

Apple was the first company to bring the concept of the modern touchscreen smartphone to consumers, and the iPhone's market share has declined significantly since it was first introduced.

In 2010, Android surpassed iOS in market share, becoming the most popular mobile operating system in the world. It's a title that Android still holds to this day. And although some may argue about which operating system is better, there is no denying which operating system is more popular as Android maintains over 80% of the global market share.

Why are Android phones more popular than iPhones?

1. More and more smartphone manufacturers are using Android

In 2007, Google and several mobile operators, software companies, and hardware companies formed the Open Handset Alliance (OHA) to compete with the launch of the iPhone. This alliance established Android as the mobile platform of choice, granting open-source licenses to manufacturers. It is this factor that makes more and more smartphone and device manufacturers use Android as the operating system for their devices. In contrast, IOS is limited to iPhones and iPads manufactured by Apple.

Additionally, regional brands and new startup manufacturers are also adopting this operating system. The boom in demand for smartphones in the Chinese and Indian markets has meant that local companies' adoption of Android has enhanced their global share of the smartphone market. Several other mobile operating systems continue to try to compete with Android and IOS like Windows Phone or Symbian.

However, when these companies failed to gain a significant foothold in the market, their smartphone brands eventually switched to Android. In fact, in the Vietnamese market, all phone companies currently use the Android operating system, and only Apple uses the iOS operating system. Android dominates in both the number of manufacturers and the number of phones produced during the year.

For example, Samsung can make up to 20 phone lines in 1 year spanning different price segments, while Apple only makes 4-5 phone lines.

2. Android devices cover a wide range of price segments

One reason why the Android operating system is more popular than iOS is because of the diverse prices of Android devices. This is extremely important for countries with developing economies and weak USD exchange rates, where even low-cost Apple smartphones are beyond the financial capabilities of the majority of users.

Not only that, the populations of India and China account for about 1/3 of the world's population, so the popularity of the Android operating system in these countries has put iOS at a big disadvantage. That is why Apple is currently promoting its business plans in these populous world markets.

3. Android devices can connect to many devices

Although Apple has opened up the IOS ecosystem to include several third-party devices, it is still a relatively closed mobile platform. However, Android has a much broader ecosystem of peripherals and wearables. This means you can have a Samsung smartwatch, a Google Home speaker, and a Huawei smartphone, and the different devices will work together.

Furthermore, data transfer and device synchronization are much simpler. This broader ecosystem attracts users who don't want to be tied to certain hardware brands. After all, if you change the Android device you use, this doesn't make all your peripherals incompatible. You can also keep many similar cables and accessories.

4. Android is becoming more and more practical

In recent years, Android has caught up to IOS in many aspects, with Google Assistant and its excellent voice control features achieving great success. Many apps that were previously iOS-only have now launched Android versions, and Google has also introduced AI to help automate your smart home. Official Google services and major app developers have significantly raised the overall quality of Android software.

Furthermore, Android integrates many expected features with each new version and improves the entire product. Now, Android phone manufacturers have paid more attention to optimizing the Android platform so that users can use the device more optimally and practically, instead of just racing for configuration like before.

5. Ability to customize and install APK files

If you are too bored with the current features and interface on your Android device You can try to customize it by installing ROMs of other platforms, something that is very difficult to do on iOS.
Due to the open-source nature of the Android operating system, anyone can obtain its source code. This also means that manufacturers, as well as independent programmers, can freely customize Android to get the best performance or remove unnecessary features.

Currently, in the Android user community, there are many ROMs with high customization, most notably EvolutionX or lineage OS, in addition to other ROMs that Make your phone simpler and optimize performance like Pixel Experience or CyanogenMod. Android group pages also have a large number of members They can help with any problems you encounter during ROM installation or use.

Besides great customization capabilities, the ability to install APK files is also an advantage for Android users to continue using old devices. Most of you will often download applications on your phone through app stores like CH Play or APPSTORE. But sometimes there are some apps you won't find on these stores for various reasons.

At this time, the ability to install APK files on Android will shine. You can also install and experience new Android builds that are often leaked in advance to use exciting new features, or download applications that are limited to certain regions so cannot be downloaded directly from the app store.

In addition, installing APK files also helps you update new application versions faster or you can even install older versions of the application to optimize for your old devices. Besides, if your device does not have access to the Play Store app store, installing the APK file will be your only choice.

In short, the diversity of Android as well as the competition between operating systems promotes a technology race between brands, helping users easily find a device that suits their financial capabilities and meets their needs meet your own needs.

[reference resources]

  • https://fptshop.com.vn/tin-tuc/danh-gia
  • https://www.thegioididong.com/tin-tuc/dien-thoai-thong-minh-da-thay-doi-cuoc-song-cua-chung-ta-1404983
  • https://medium.com/android-news/the-best-android-sdk-tools-of-the-year-b546f66edf28
  • https://support.google.com/android/answer/12761388?hl=en
View More
TECH

December 5, 2023

What is Docker Registry?

If you deploy an application inside a container, you may already use a Docker Registry. The Docker Registry provides a simple, secure, and easily extensible way for developers to distribute images and for users to search and download them.

This article will introduce the basic information about Docker Registries and how to create a private Docker Registry.

What is Docker Registry?

Simply, Docker Registry is a tool provided by the Docker project that helps store and distribute containers images. Docker Registry is open source and everyone can download and run for storing your own images.

More broadly, we can understand it as a tool used to store and distribute container images and the Docker project's Docker Registry is a solution, but there are other solutions such as:

  • Harbor (an open source option).
  • Docker Hub (a solution from Docker).
  • JForg Artifactory (a tool to store container images in both on-premises and cloud environments).
  • Amazone Elastic Container Registry (a Docker Registry service in the AWS cloud).
  • Azure Container Registry (a solution from Azure).
  • Google Cloud Container Registry.

How to create a Docker Registry.

When using Docker, people often use container images from Docker Hub.

However, there are some limitations of Docker Hub such as:

  • The server is located abroad, so when the international network has problems, downloading container images will take a lot of time.
  • Network restrictions for security purposes at some tech companies will also make downloading images from Docker Hub more difficult.
  • In some cases, you don't want to make your container images public and the Docker Hub will charge you for the images you host as private. In case you have many percentages of images, the cost is quite a lot of money

With the above information, you can build your own Docker Registry to serve the needs of storing and distributing these container images for project development purposes.

Below are instructions for running a Docker Registry, creating, and pushing a container image to the Docker Registry.

Creating a Docker container from image registry:2

docker run -d -p 5000:5000 --name registry -v C:/Users/pbqtai/docker-registry:/var/lib/registry registry:2

Creating and pushing a container image to the newly created registry.

docker pull php:7.4.33-fpm

Using the below command to perform image tagging.

docker image tag php:7.4.33-fpm localhost:5000/php:7.4.33-fpm

Perform image push to registry server.

docker push localhost:5000/php:7.4.33-fpm

To check whether the container image has been saved in the Docker Registry or not, you can access the url: http://localhost:5000/v2/_catalog

To use this image, type the below command:
docker pull localhost:5000/php:7.4.33-fpm 

Now the image will be loaded from the Docker Registry we just created instead of from the Docker Hub.

Hopefully the above information, you can understand more about the Docker Registry and can creating a simple Docker Registry for yourself.

[Reference Source]

  1. https://appmaster.io/blog/docker-container-overview (Source of images)
  2. https://hub.docker.com/_/registry
  3. https://sysdig.com/learn-cloud-native/container-security/what-is-a-docker-registry/

 

 

View More
TECH

December 5, 2023

Some tips to improve SQL query performance

Improving SQL query performance is important in applications or systems. Improving SQL query performance helps execute queries faster, leading to faster data access. Applications with optimized SQL queries provide a better user experience.

Many solutions can improve SQL query performance such as: adding an index, avoiding using subqueries, using a partition, avoiding query in a loop, selecting fields instead of selecting *, using a matching join instead of a subqueries, etc. In this article, I will introduce some tips to improve SQL performance in SELECT and INSERT queries. It may be helpful for newbies.

  1. Use SELECT fields instead of SELECT *
    Retrieving all columns with SELECT * may result in unnecessary data transfer between the database and the application. This can lead to increased network traffic and slower query performance, especially when dealing with large datasets. So, we should only select the necessary fields.



  2. Use Join instead of subquery

    Using subqueries in SQL is not inherently bad, and they can be one of the best ways to express complex logic in queries. However, there are situations where using a subquery can impact performance, and developers should be cautious in these situations.

    In many cases, JOINs can be more efficient than subqueries, especially when dealing with large datasets. In such cases, alternatives like JOINs can often lead to better performance.



  3. Avoid query in a loop

    Executing frequent queries in a loop can place a significant load on the database server. This loading can lead to performance degradation, slow response times, etc. In a loop, if a query is performed repeatedly to retrieve from the database, consider fetching all necessary data in a query before entering the loop, which reduces the number of interactions with the database.

    Avoiding queries in loops is one of the best ways that improve the efficiency and performance of your application.

  4. Insert multiple rows using a query statement

    Improving the performance of SQL INSERT operations is important for efficient data loading, especially in situations where large amounts of data need to be inserted.

    Instead of performing individual INSERT statements for each record, consider using batch inserts. Batch inserts allow you to insert multiple records with a single SQL statement, reducing the number of round-trips to the database and improving overall performance.

    Batch inserts can lead to improved performance, especially when inserting a large volume of data. The overhead associated with processing each INSERT statement is minimized, resulting in faster data insertion.



    Note: There are several important considerations and notes when using batch insert with large amounts of data. That is out of memory in the server.

    Example:  When inserting 20 thousands data from csv file, the memory problem will occur if the configuration memory setting in your server is low. The problem is as below.

    To resolve this issue, you can review and adjust the memory configuration settings for your server or divide the data into smaller parts.

    Now I will introduce the solution of dividing the data into smaller parts.

    The data is stored in the csv file as below:


    I will divide the data in the file into 3 parts, and in each part I will insert 2 records into the database:

    Loop1 (part1): Read file from line 2 to line 3 -> insert into database

    Loop2 (part2): Read file from line 4 to line 5 -> insert into database

    Loop3 (part3): Read file from line 6 to line 7 -> insert into database

    The code I have implemented is as below:

    When you need to insert large amounts of data, Instead of inserting all the data into one transaction, split the data into smaller batches. This helps manage memory usage more effectively.

    In summary, optimizing SQL queries can significantly improve query performance and enhance the overall efficiency of the database. It directly impacts user satisfaction. Regular performance tuning and optimization are essential components to maintaining a high-performance system.

    [Reference]
    https://www.techagilist.com/mainframe/db2/sql-query-optimization-tips-tricks/

View More
TECH

December 3, 2023

How to use 2D Graphics in .NET MAUI app

.NET Multi-platform App UI (.NET MAUI) is a framework for building modern, multi-platform, natively compiled iOS, Android, macOS, and Windows apps using C# and XAML in a single codebase [3]. This blog show how to use draw a graphical object in .NET MAUI app.

View More
TECH

December 3, 2023

5 things awesome Google Sheets you can do at work

I usually use Google Sheets at work. It has a clean interface. it’s easy to collaborate with other people in projects. In few case, it's save me more time than other ticket management software. I'm going to show you some tips that will help you save time and do some useful things, Let’s get started!

View More
TECH

December 1, 2023

What does Critical Thinking mean to Developers?

Critical thinking is a valuable skill for developers, as it helps them approach programming challenges, design decisions, and problem-solving tasks in a thoughtful and systematic way.

View More
TECH

November 30, 2023

Flux Architecture with QML

 
In 2014, during the Hacker Way conference, Facebook introduced Flux architecture as an alternative to MVC.
Flux architecture is a software design pattern that helps manage the flow of data in complex applications.
It provides s unidirectional data flow, which makes it easier to understand, maintain, and debug applications.
 

1. What is Flux architecture

Flux is an architectural pattern proposed by Facebook.
These are four parts: Actions, Dispatcher , Stores, Views

 

Actions:  Contains all information necessary to do some action
 
Dispatcher: Is a Single Object that broadcast (actions) to all stores
 
Stores:  Manages the state ( data  ), the store is an event emitter
 
Views: Is the user interface component, Views listen for store changes
 

2. Flux architecture with QML

 

 

Views:  Are QML files
 
Actions: Is a Data type that include event name and data
 
Dispatcher: Is Singleton design pattern that is control center forward actions to all stores
 
Stores:  Use C++ models with QML
 
The following application creates a Data Object class with Q_PROPERTY values that will be accessible as named roles when a QList<DataObject*> is exposed to QML
 
 
3. Why do we should use Flux architecture
 
Today, there are two popular architectures : MV*( Model-View-Control, Model-View-Presenter, …) and  flux
Comparison table between  MVC and Flux architecture
 
 
Merit & Demerit
 
 
4. Demo source

You can refer the below Demo source code.

DemoFluxSrc

 

[Reference Source]

  • https://doc.qt.io/qt-5/qtquick-modelviewsdata-modelview.html
  • https://www.infoq.com/news/2014/05/facebook-mvc-flux/
  • https://www.voidcanvas.com/flux-vs-mvc/
View More
TECH

November 29, 2023

Let's learn VBA together

   VBA stands for Visual Basic Application, which is a basic programming application in Microsoft Office. For someone who doesn't know about programming or IT, we will be a little confused when hearing about the concept of of VBA, right? However, it's actually more accessible than you think.

View More
TECH

November 29, 2023

Laravel - Some tips to optimize Laravel's performance

Laravel has been a famous framework since 2011. This framework can help us develop a project faster than it did with a lower effort. But one of the most important things when we use a framework is performance.

Luckily, Laravel has supported many helpful features to optimize performance (Redis, Memcache, DB support, etc).

There are many factors that can negatively affect your web application, including poor code quality, inefficient server configurations, and insufficient resources.

However, we can use some tips to improve your website.

1. Update to the latest version of PHP and Laravel

It seems quite obvious but it is the simple way to improve your web application. This may be a challenge with a large legacy application while updating the version. But using the latest version can help us with numerous benefits: new features, bug fixes, and security.

2. Using the Artisan Command

One of the best features in Laravel is called Artisan. Artisan is a command-line tool. It will improve your web performance if you use it in the right way. The easy way is that you can cache the route as well as config with a command line.

php artisan config: cache

php artisan route: cache

Route Caching: This is a critical tool, especially for applications that have a large number of routes. With caching, Laravel only refers to the file where the cached routes are stored (bootstrap/cache/routes.php) instead of rendering all the routes in your website (This will cause slow performance).

Config Caching: Similar to route caching, it will find all data of the config file and variables of .env file then store it in bootstrap/cache/config.php

Remember that you need to run the command above if you have changed any in the config file or route file. To clear the cache, you can run these commands:

php artisan config: clear

php artisan route: clear

3. Remove unused service

The key goal of Laravel is to bring an easy development process to the developers.

When launching Laravel, it will auto-load many service providers listed within the config/app.php file to help you get started with your project.

In addition, many developers don’t want to follow the default framework settings. So it’s necessary to delete unused services to improve your project performance.

4. Eager Loading

All of the queries in Laravel are lazy queries when you execute. It only fetches the required data. Sometimes, this will increase the number of queries and cause low performance for your website. You will run up to N+1 queries to find your response.

To resolve the N+1 queries problem, Laravel provides us with a feature that can use eager loading to load the data to help us improve performance.

Let's compare the source code of two loading modes:

Lazy Loading: You will need to execute multiple queries to find the response you need.

$books = Book::all(); // Get all books

foreach($books as $book) {

echo $book->author->name // Executing query to find author link with book

}

Eager Loading: You only need to execute once.

$books = Book::with('author')->get(); // Get all books link with author

foreach ($books as $book) {

echo $book->author->name // Not execute query again to find

}

Conclusion

Laravel is a fast-growing PHP framework, that has many useful features to support users to improve the performance of their websites.

Hopefully, some tips that I introduced above can help you somewhat in optimizing your website performance.

 

Reference:

  1. Ultimate Laravel Performance Optimization Guide (cloudways.com)
  2. 17 Methods to Optimize Laravel Performance (kinsta.com)
View More
1 11 12 13 14 15 17
Let's explore a Partnership Opportunity

CONTACT US



At ISB Vietnam, we are always open to exploring new partnership opportunities.

If you're seeking a reliable, long-term partner who values collaboration and shared growth, we'd be happy to connect and discuss how we can work together.

Add the attachment *Up to 10MB