Beginner C++ tutorial: ObjectBox installation

Beginner C++ tutorial: ObjectBox installation

This ObjectBox beginner tutorial is for people who have limited knowledge of C++ development (no prior experience with external libraries is required). It will walk you through the installation process of all the development tools needed to get started with ObjectBox on Windows. By the way, ObjectBox is a database with intuitive native APIs, so it won’t take you long to start using it.

Firstly, we will need to set up a Linux subsystem (WSL2) and install such tools as:

  • CMake, which will generate build files from the ObjectBox source code to work on Linux;
  • Git, which will download the source code from the ObjectBox repository.

Then, we will install ObjectBox and run a simple example in Visual Studio Code.

Windows Subsystem for Linux (WSL2)

In this section, you will set up a simple Linux subsystem that you can use to build Objectbox in C++.

  1. Install WSL (Note: this requires a reboot; it also configures a limited HyperV that may cause issues with e.g. VirtualBox).
    Warning: to paste e.g. a password to the Ubuntu setup console window, right-click the title bar and select Edit → Paste. CTRL + V may not work.
  2. (optional, but recommended) install Windows Terminal from Microsoft Store and use Ubuntu from there (does not have the copy/paste issue, also supports terminal apps better).
Windows Terminal in the Microsoft Store

3. Within Windows Terminal, open Ubuntu by choosing it from the dropdown menu.

Drop-down menu in Windows Terminal, through which a new tab for Ubuntu can be opened

4. Get the latest packages and upgrade:

5. Install build tools

Install ObjectBox using CMake

Now that you have WSL2 and all the packages, we can switch to VS Code and install ObjectBox with the help of CMake.

  1. In Ubuntu, create a new directory and then open it in Visual Studio Code:

2. Install the following extensions:

Extensions tab in Visual Studio Code, showing what needs to be installed in this tutorial: C/C++, CMake Tools and Remote - WSL

3. Create a text file called CMakeLists.txt with the following code. It will tell CMake to get the ObjectBox source code from its Git repository and link the library to your project.

4. Create a simple main.cpp file that will help us verify the setup:

5. Follow this official guide for VS code and CMake to select Clang as the compiler, configure and build ObjectBox. As a result, .vscode and build folders will be generated. So your directory should now look like this:

Explorer tab in Visual Studio Code, showing the two new folders that were generated after a successful build

Running the tasks-list app example

Finally, we can check that everything works and run a simple example.

1. Click the “Select target to launch” button on the status bar and select “myapp” from the dropdown menu. Then launch it. You should see it output the correct version as in the screenshot.

"Select launch target" menu in Visual Studio Code
Output of main.cpp, verifying the version of ObjectBox used and demonstrating that the C++ build files were generated correctly.

2. Before proceeding with the example, you need to download the most recent ObjectBox generator for Linux from releases. Then come back to the Windows Terminal and type

to open the current directory in Windows Explorer. Copy the objectbox-generator file in there.

3. Back in VS Code, you should now run the generator for the example code:

If you get a “permission denied” error, try this to make the generator file executable for your user:

4. Now choose objectbox-c-examples-tasks-cpp-gen as the target and run it. You should see the menu of a simple to-do list app as shown on the screenshot. It stores your tasks, together with their creation time and status. Try playing around with it and exploring the code of this example app to get a feel of how ObjectBox can be used.

Output of the Objectbox C++ tasks-list app example showing its menu with available commands

Note: if you see a sync error (e.g. Can not modify object of sync-enabled type “Task” because sync has not been activated for this store), please delete the first line from the tasklist.fbs file and run the objectbox generator once again. Or, if you want to try sync, apply for our Early Access Data Sync. There is a separate example (called objectbox-c-examples-tasks-cpp-gen-sync) that you can run after installing the Sync Server.

ObjectBox Database Java / Kotlin 3.0 + CRUD Benchmarks

ObjectBox Database Java / Kotlin 3.0 + CRUD Benchmarks

The Android database for superfast Java / Kotlin data persistence goes 3.0. Since our first 1.0-release in 2017 (Android-first, Java), we have released C/C++, Go, Flutter/Dart, Swift bindings, as well as Data Sync and we’re thrilled that ObjectBox has been used by over 800,000 developers.

We love our Java / Kotlin community ❤️ who have been with us since day one. So, with today’s post, we’re excited to share a feature-packed new major release for Java Database alongside CRUD performance benchmarks for MongoDB Realm, Room (SQLite) and ObjectBox.

What is ObjectBox?

ObjectBox is a high performance database and an alternative to SQLite and Room. ObjectBox empowers developers to persist objects locally on Mobile and IoT devices. It’s a NoSQL ACID-compliant object database with an out-of-the-box Data Sync providing fast and easy access to decentralized edge data (Early Access).

New Query API

A new Query API is available that works similar to our existing Dart/Flutter Query API and makes it easier to create nested conditions:

In Kotlin, the condition methods are also available as infix functions. This can help make queries easier to read:

Unique on conflict replace strategy

One unique property in an @Entity can now be configured to replace the object in case of a conflict (“onConflict”) when putting a new object.

This can be helpful when updating existing data with a unique ID different from the ObjectBox ID. E.g. assume an app that downloads a list of playlists where each has a modifiable title (e.g. “My Jam”) and a unique String ID (“playlist-1”). When downloading an updated version of the playlists, e.g. if the title of “playlist-1” has changed to “Old Jam”, it is now possible to just do a single put with the new data. The existing object for “playlist-1” is then deleted and replaced by the new version.

Built-in string array and map support

String array or string map properties are now supported as property types out-of-the-box. For string array properties it is now also possible to find objects where the array contains a specific item using the new containsElement condition.

Kotlin Flow, Android 12 and more

Kotlin extension functions were added to obtain a Flow from a BoxStore or Query:

Data Browser has added support for apps targeting Android 12.

For details on all changes, please check the ObjectBox for Java changelog.

Room (SQLite), Realm & ObjectBox CRUD performance benchmarks

We compared against the Android databases, MongoDB Realm and Room (on top of SQLite) and are happy to share that ObjectBox is still faster across all four major database operations: Create, Read, Update, Delete.

Android database comparative benchmarks for ObjectBox, Realm, and Room

We benchmarked ObjectBox along with Room 2.3.0 using SQLite 3.22.0 and MongoDB Realm 10.6.1 on an Samsung Galaxy S9+ (Exynos) mobile phone with Android 10. All benchmarks were run 10+ times and no outliers were discovered, so we used the average for the results graph above. Find our open source benchmarking code on GitHub and as always: feel free to check them out yourself. More to come soon, follow us on Twitter or sign up to our newsletter to stay tuned (no spam ever!).

Using a fast on-device database matters

A fast local database is more than just a “nice-to-have.” It saves device resources, so you have more resources (CPU, Memory, battery) left for other resource-heavy operations. Also, a faster database allows you to keep more data locally with the device and user, thus improving privacy and data ownership by design. Keeping data locally and reducing data transferal volumes also has a significant impact on sustainability.

Sustainable Data Sync

Some data, however, you might want or need to synchronize to a backend. Reducing overhead and synchronizing data selectively, differentially, and efficiently reduces bandwidth strain, resource consumption, and cloud / Mobile Network usage – lowering the CO2 emissions too. Check out ObjectBox Data Sync, if you are interested in an out-of-the-box solution.

Get Started with ObjectBox for Java / Kotlin Today

ObjectBox is free to use and you can get started right now via this getting-started article, or follow this video.

Already an ObjectBox Android database user and ready to take your application to the next level? Check out ObjectBox Data Sync, which solves data synchronization for edge devices, out-of-the-box. It’s incredibly efficient and (you guessed it) superfast 😎

We ❤️ your Feedback

We believe, ObjectBox is super easy to use. We are on a mission to make developers’ lives better, by building developer tools that are intuitive and fun to code with. Now it’s your turn: let us know what you love, what you don’t, what do you want to see next? Share your feedback with us, or check out GitHub and up-vote the features you’d like to see next in ObjectBox.

Dart Flutter Database ObjectBox 1.0 Release

Dart Flutter Database ObjectBox 1.0 Release

In 2019 we first introduced the ObjectBox database v0.1 for Flutter/Dart. Our team has loved the engagement and feedback we’ve received from the developer community since, and we’re thrilled to announce the first stable version 1.0 for ObjectBox Dart/Flutter today.

With this release we bring you the fast and easy to use ObjectBox database for Dart objects: optimized for high performance on mobile and desktop devices. ObjectBox persists your Dart objects (null safe, of course) and comes with relations, queries, transactions, and Data Sync. For a feature list and more, please also check the pub.dev page.

ObjectBox by Example

For those of you new to ObjectBox, here is how you can use it (or check the docs if you want to dive deep right away). By annotating a class with @Entity you tell ObjectBox that you want to persist its objects, which is done putting the object in a Box:

What’s new with the 1.0?

Version 1.0 delivers a stabilized API and adds new essential features like async writes and query streams. We’ve also extended support for Flutter desktop. Let’s look at queries and how they can be used depending on the use case:

There are two new approaches to do async puts for asynchronous database writes: putAsync() returns a Future to check if the call was successful.

Or you can use a background queue if you don’t need individual Futures, the following code inserts 100 objects and only waits once:

If you are interested in further improvements we made to 1.0, please check out the full changelog.

Dart Flutter Database Benchmarks

ObjectBox Dart v1.0 also comes with considerable optimizations bringing a new level of database performance to Flutter apps. ObjectBox enables data-heavy apps that were not possible on Flutter before. Consider this a first sneak-peek; stay tuned for detailed performance benchmarks to be released including queries (hint: they are really fast) along with updated benchmarking code.

What we tested

We looked at some two popular approaches: sqflite, a SQLite wrapper for Flutter (no Dart Native support), and Hive, a key-value store with Class-adapters which seems still popular although its creator abandoned it for architectural shortcomings (it has memory problems and does not support queries). In the previous benchmark we’ve also had a look at Firestore, but being an online-only database it was thousands of times slower than the rest so we’ve left it to rest this time around. Check our previous benchmark if you’re interested.

To get an overview of the databases, we tested CRUD operations (create, read, update, delete). Each test was run multiple times and executed manually outside of the measured time. Data preparation and evaluation were also done outside of the measured time.

ObjectBox, sqflite, Hive performance comparison across CRUD

Looking at the results, we can see ObjectBox performing significantly faster than sqflite across the board, with up to 100 time speed-up in case of create & update operations. Compared to Hive, the results are a little closer in some cases (read) though ObjectBox still comes out on top in all the metrics. Considering that Hive keeps all Dart objects in memory (!) while ObjectBox does not, should give you a good impression of how fast object persistence with ObjectBox is.

ObjectBox Database for Flutter/Dart Highlights

For those of you new to ObjectBox, here’s a quick summary of what our super-fast embedded database offers, out of the box:

  • automatic schema migration: adding new classes or fields just works
  • type-safe APIs, e.g. no interface{} arguments
  • embedded edge database – no server needed, store all data directly on the device
  • no ORM, no SQL
  • relations: to-one, to-many (eager and lazy fetching)
  • robust query support, including indexes for scalable lookups
  • Support for implicit (automatic) and explicit (user defined)
  • transactions: ACID compliant with superfast bulk/batch operations
  • low memory usage
  • runs across operating systems: 64-bit Linux, macOS, Windows, small 32-bit ARM-based Linux devices (e.g. Raspberry Pi)
  • Data Sync: an efficient and easy way to synchronize data between your app and the cloud

Getting Started with ObjectBox for Flutter/Dart Today

ObjectBox is free to use and you can get started right now with the Flutter database on GitHub, via the docs, pub.dev, or this getting-started video tutorial, or getting-started article.

We ❤️ your Feedback

Now it’s your turn: let us know what you love, what you don’t, what do you want to see next? Share your feedback with us, or check out GitHub and up-vote the features you’d like to see next in ObjectBox.

Flutter databases –  hive, ObjectBox, sqflite (+ Drift, floor)

Flutter databases – hive, ObjectBox, sqflite (+ Drift, floor)

Flutter, the renowned cross-platform mobile framework, has been gaining immense popularity among developers worldwide. As the Flutter community expands, the demand for efficient Flutter databases is also increasing. Developers now have access to a range of Flutter database options that cater to various needs and preferences.

In this article, we’ll focus specifically on local storage solutions, as these are essential for enabling offline functionality, improving performance, ensuring data persistence, enhancing data privacy and security, and supporting edge computing capabilities. Furthermore, local data storage is needed to promote sustainability. Let’s dive into the current local database landscape for Flutter and compare the most popular options.

Flutter databases / Flutter Dart data persistence

While the database market is huge and dynamic,  there are only few options to choose from if you are a Flutter / Dart app developer. Before we dive into the Flutter database options, advantages and disadvantages, we’re taking a very quick look at databases to make sure, we share a common ground. 

What is a database?

A database is a piece of software that allows the storage and systematic use of digital information, in other words: data persistence. As opposed to mere caching, data is reliably stored and available to work with unless actively deleted. A database typically allows developers to store, access, search, update, query, and otherwise manipulate data in the database via a developer language or API. These types of operations are done within an application, in the background, typically hidden from end users. Many applications need a database as part of their technology stack. The most typical database operations are CRUD: Create, Read, Update, Delete.

What are the major types of databases?

There are many types of databases. For our purpose, the most important differentiations are non-relational (NoSQL) versus relational databases (SQL), cloud databases versus edge databases, and maybe embedded versus in-memory. However, databases can be further distinguished by additional criteria e.g. the data types they support, or the way they scale – and definitions can vary.

What is an ORM?

An Object relational Mapper (ORM) is not a database. We’re bringing this up mainly, because we see it confused often. It is a layer that sits on top of a database and makes it easier to use. This is typically especially relevant when the database is a relational database (SQL) and the programming language used is object-oriented. As noted above, Dart is an object-oriuented programming language.

The Flutter local data persistence landscape

There are several Flutter databases that provide offline support, offering the ability to store and access data locally even without an internet connection. Here are some of the notable options:

  • Hive is a lightweight key-value database written in Dart for Flutter applications, inspired by Bitcask.
  • ObjectBox DB is a highly performant lightweight NoSQL database with an integrated Data Sync. It stores objects.
  • sqflite is a wrapper around SQLite, which is a relational database without direct support for Dart objects. 
  • Drift is a reactive persistence library for Flutter and Dart, built ontop of SQLite. 
  • Floor is another ORM on top of SQLite.

 

What is the best offline Flutter Dart database?

This of course depends… Make up your own mind with the following comparison matrix as a starting point. Note: With very few options to choose from, the following overview is sometimes a bit like comparing apples 🍎 and pears 🍐.

Name Description Primary Model Language License Data Sync
Hive Lightweight key-value database NoSQL Dart Apache 2.0
ObjectBox Lightweight NoSQL database with integrated Data Sync NoSQL Dart Bindings are Apache 2.0
Drift ORM on top of SQLite relational SQL SQLite is public domain, Drift is MIT
Floor ORM on top of SQLite relational SQL SQLite is public domain, Floor is Apache 2.0
sqflite SQLite plugin for Flutter relational SQL SQLite is public domain, sqflite lib is MIT
<body> <p>Diese Seite verwendet Frames. Frames werden von Ihrem Browser aber nicht unterstützt.</p> </body>

Flutter Database performance benchmarks

As with any benchmark, you need to take a look at the details. We take benchmarking very serious and strive to get accurate results. Therefore, we also always open source the benchmarking code and encourage you to check it out. If you note anything that does not even out in your oppinion, do let us know. We have a long history of updating and improving our benchmarks continually and are happy to take any recommendations.

Performance Benchmark Test Setup

We used an Android 10 device with a Kirin 980 CPU to run the benchmarks as a Flutter app. The app executed all operations (ops) in batches of 10.000 objects. Each batch formed a single transaction. We ran each test 50 times. The results you see in the diagram are averages across all runs. We set it up that way to ensure that neither the Virtual Machine warmup during the first run nor the garbage collections affect the overall result significantly. 

Flutter Databases CRUD Performance Results

Summary of the Flutter Dart DB Benchmarks

Hive and ObjectBox clearly outperform sqflite across all CRUD operations. The results show ObjectBox performing with up to 70 times the speedup for create and update operations. With regards to comparing Hive and ObjectBox, the results vary more. Hive can be faster at reading objects than ObjectBox. However, strictly speaking it’s not a fair comparison, because in Hive, the high read numbers result from Dart objects already cached in memory. If the objects are fetched using the async API from disk, the numbers drop by factor 1000.

Drift and Floor were not part of the benchmarking as they are ORMs. However, it is very likely they will perform similarly to sqflite, reflecting primarily the performance of SQLite.

Flutter Data persistence – Conclusion

Recently, the Flutter database landscape has experienced significant growth and diversification. With Flutter’s increasing popularity, developers now have a number of database options available. In this article, we focused on the best local databases, comparing their features in a comprehensive matrix, and showcasing performance benchmarks. In the end, the best choice depends on the specific needs of each project. The Flutter database landscape in 2023 is a thriving ecosystem, continuously evolving to meet the changing needs of Flutter app development. One upcoming change that we can see is the rise of vector databases for AI. So, we encourage you to keep an eye on the lively market of Flutter databases not to miss any important updates.

If you want to get started learning how to use a database, we suggest you check out this video tutorial series that teaches you how to build a Flutter app with ObjectBox from scratch.

 

ObjectBox Dart/Flutter v0.11 Database: Performance & Relations

ObjectBox Dart/Flutter v0.11 Database: Performance & Relations

Flutter Databases are few. Therefore, we’re happy to take a big step towards 1.0 with this ObjectBox Dart v0.11 release, improving performance and bringing the much-desired relations support known from other ObjectBox DB language bindings to Dart/Flutter.

For those of you new to ObjectBox: ObjectBox is a superfast NoSQL object database for Flutter / Dart and here is how you can save data in your Dart / Flutter apps:

To learn about more ObjectBox features, like relations, queries and data sync, check our ObjectBox pub.dev page.

How fast is ObjectBox Dart? Performance Benchmarks

Speed is important for data persistence solutions. Accordingly, we wanted to test how ObjectBox compares performance-wise to other Flutter Dart database options. Therefore, we looked for libraries with comparable levels of storage abstraction and feature set –  so not just plain SQL/Key-value storage but also ORM-like features. There doesn’t seem to be that much choice… 

We looked at some two popular approaches: sqflite a SQLite wrapper for Flutter (no Dart Native support), and Hive, a key-value store with Class-adapters which seems still popular although its technology is phased out (see below). As a third alternative we pulled in Firestore, which does not really fit as it is no local database, but would be fun to compare anyway.

What we tested

To get an overview of the databases, we tested CRUD operations (create, read, update, delete). Each test was run multiple times and executed manually outside of the measured time. Data preparation and evaluation was also done outside of the measured time.

We tried to keep the test implementations as close as possible to each other while picking the approaches recommended by the docs for each database. We open sourced the test code at https://github.com/objectbox/objectbox-dart-performance if you want to have a closer look.

Performance Benchmark Results

Looking at the results, we can see ObjectBox performing significantly faster than sqflite across the board, with up to 70 times speedup in case of create & update operations. Compared to Hive, the results are a little more varied, with Hive being faster at reading objects than ObjectBox (we come to that later in our outlook), and ObjectBox being faster at creating objects, about four times faster at updates and three times for deletes. As a mostly-online database, it becomes clear that Firestore’s performance is not really comparable.

Implementation notes

ObjectBox: This release largely boosted the performance. The remaining bottlenecks are due to Dart itself and how it allows to modify byte buffers. There’s potential to double the speed if we look at other languages supported by ObjectBox. And if that’s not happening soon, we’d still have the option to do some low-level hacks…

Sqflite: a wrapper around SQLite, which is a relational database without direct support for Dart objects. Each dart object field is mapped to a column in the database, as per sqflite docs, i.e. converting between the Dart class and a Map.

Hive: We’ve tested with the latest Hive release, which is technically discontinued. The author hit two architectural roadblocks (RAM usage and queries) and is currently in the process to do a rewrite from scratch.
Update: strictly speaking it’s not straightforward to directly compare e.g. ObjectBox vs. Hive. In Hive, the high read numbers result from Dart objects already cached in memory. If the objects are fetched using the async API from disk, the numbers drop by factor 1000.

Firestore: This is totally apples and oranges, but we still decided to include Firebase/Firestore as it seems at least somewhat popular to “persist data”. It’s quite Cloud centric and thus offers limited offline features. For example, in order to use batches (“transactions”), an internet connection is required to “commit”. Also, due to its low performance, the test configuration was different: batches of 500 objects and only 10 runs.

Test setup

We ran the benchmarks as a Flutter app on a Android 10 device with a Kirin 980 CPU. The app executed all operations in batches of 10.000 objects, with each batch forming a single transaction. Each test was run 50 times, averaging the results over all the runs. This ensured the VM warmup (optimization) during the first run and garbage collections don’t affect the overall result significantly. (We care about accurate benchmarks; read more about our benchmarking best practices here.)

Outlook

With this latest release, we’re not far away from a stable API for a 1.0 release (🎉), so please share your thoughts and feedback. For the next release, we’ll add features like async operations, more relation types and some smaller improvements. We are also working on an ObjectBox variant for the Web platform that is planned close to the 1.0 release. And of course there is ObjectBox Data Sync for Flutter/Dart. If you want to be first in line to try, drop us a line, we can put you on the shortlist.

ObjectBox Swift 1.4 – In Relation to…

ObjectBox Swift 1.4 – In Relation to…

ObjectBox for Swift 1.4 makes object relations more natural and intuitive for Swift developers. For example, let’s take the teacher-student relation to Swift and how you store objects in the database. Let’s say “Teacher” is a Swift class that has a collection called “students”. Now let’s say we have a new teacher with new students and want to store them in the ObjectBox database. It’s done like this:

let yoda = Teacher(name: "Yoda")
yoda.students.append(Student(name: "Luke"))
yoda.students.append(Student(name: "Anakin"))
try box.put(yoda)

This is pretty much standard Swift. A single put command is enough to store all three new objects in the database (sorry for the “try”, Yoda, but you know, IO…). Now let’s see how this works. The students’ property in the Teacher’s class is of type ToMany<Student> and works like any Swift collection. This is because ToMany implements the protocols RandomAccessCollection and RangeReplaceableCollection. Under the hood however, it tracks all changes. Thus, when ObjectBox is instructed to put Yoda in a box, it also knows that two students were added. It also knows that our two Jedi students are new and thus puts them in database too. If you supply students that have been already persisted, it won’t put them. You can also mix new and existing objects.

Version 1.4 does not only bring TooMany (sic) improvements, but also brings a couple of new features, e.g. a bulk-get and read-only stores. You also may have heard of Sync (some kind of teleportation for objects, my young padawan). We’re still working on that, but we started to expose the Sync API with this release. It doesn’t come with any (space consuming) implementation so it’s really about getting early awareness and feedback. A full changelog is available at the docs.

So, time to start your (cocoa) pod again and let us know what you think. May the for… um, OK, that’s getting too many references for one article. One to many.