DEV Community

Nishant Keshav
Nishant Keshav

Posted on

ORMs: The Good, The Bad, and The Ugly Performance

Ever opened your code editor and thought, “Great, another day wrestling with SQL queries and database schemas”? You’re not alone. For centuries (give or take a couple of decades), developers have been banging their heads against the keyboard, translating their lovingly crafted objects into cryptic SQL statements.

Enter the superhero you never knew you needed: ORM (Object-Relational Mapping). Imagine telling your database, “Hey, save this,” and—poof!—The ORM handles the nitty-gritty SQL complexity for you.

Think of ORM as your multilingual friend who effortlessly translates your instructions between you (the code) and the database. No more lost-in-translation moments – thanks to ORM! Come on, let’s dive deeper into the world of ORM in this blog today.

Let’s say you have this object with you:

{
  rollNo: 7 
  name: "Nishant"
  sub: "JAVA"
}
Enter fullscreen mode Exit fullscreen mode

Now, imagine a scenario where storing this object is as seamless as a magical process. Behind the scenes, all the required database operations happen automatically. No need for you to write the SQL queries – YES, this is possible!

This is where ORM steps in!

What is an ORM?

An ORM is a tool that lets you work with a database using programming code instead of writing SQL directly. You can perform CRUD operations (Create, Read, Update, Delete) by following the ORM's specific syntax to manage data in the database easily.

So, let me take you through an example.

Here's an example of SQL code that retrieves information about a particular user from a database:

SELECT id, name, email, country, phone_number FROM users WHERE id = 20
Enter fullscreen mode Exit fullscreen mode

The code above returns information about a user's name, email, country, and phone number from a table called users. Using the WHERE clause, we specified that the information should be from a user with an ID of 20.

On the other hand, an ORM tool can do the same query as above with simpler methods. That is:

users.GetById(20)
Enter fullscreen mode Exit fullscreen mode

So the code above does the same as the SQL query. Note that every ORM tool is built differently, so the methods are never the same, but the general purpose is similar.

Now, coming back to the Original Example

For instance, if you have a student object with properties like student ID (rollNo), name, and subject (as given in the image above), you collect these values. All these things are available in the object format, in the variables format. Subsequently, to store this information in a database, you employ a SQL query.

INSERT into student values (07, ‘Nishant’, ‘JAVA’);
Enter fullscreen mode Exit fullscreen mode

So, most of the people would execute the query given above to add the student details to the students' database.

Every interaction with the database involves SQL queries. Whether you're inserting data into a table, fetching information using a select query, or updating records with an update query, SQL is at the core of these operations. This means that as a developer, you need to have a good understanding of SQL.

Imagine you have some data in your program, like an object, and you want to save it to a database. Normally, you would write SQL queries to do this, which can be a bit tricky. But what if you didn’t have to write those SQL queries yourself?

Instead, you just tell the system, “Save this object,” and it takes care of everything for you. Behind the scenes, the system automatically turns your object into the right SQL commands and saves it in the database. You don’t see or write the SQL, but it’s still happening(kind of magic, right?)

Your DBMS only works with SQL queries, so you can't say there's no SQL. There is SQL, but you, as a programmer, are not directly writing it. However, you have tools/libraries that assist you in managing this process, ensuring you don't have to manually write the SQL queries.

These techniques are called ORM techniques, which stand for Object Relational Mapping.

You incorporate this technique between your framework and any programming language and your database.
Image description
Basically, you are actually talking to ORM, and this will store the data in the database. Who is responsible for making the SQL queries? This ORM! You don't have to do anything.

But is it possible? Can we just save the data in the database by using the object? The answer is YES!.

Let's consider how we create an object in JAVA.
(If you are asking why Java, because I am a Java developer😏.)

In Java, you require a class to create an object. This class serves as your design blueprint.

Let's say if you talk about students, you will create only one student class, and you will have multiple objects.

class Student { 
    int rollNo;
    String name;
    String sub; 
}
Enter fullscreen mode Exit fullscreen mode

Imagine you have a classroom with 20 students. For each student, you will have a distinct object. Each of these objects will have a unique roll number, a different name, and possibly a different or common subject of interest.

Image description

When considering creating tables in a database, think of it as having a box with multiple columns and rows.

At the beginning of the application, you don't have any data; you just have the column structure. You might have a "roll number" column, a "name" column, and a favourite “subject" column.

🔢 Roll No 🧑 Name 🎯 Subject
🟢 01 Rohit 🐍 Python
🔵 02 Jani ☕ Java
⚪ .. .. ..
🔴 20 Saira #️⃣ C#

We are basically trying to relate object-oriented concepts with database concepts, and that is what is called Object-Relational Mapping. Okay, so you don't have to do anything as a programmer.

When we talk about Java we have HIBERNATE, if you talk about Django which uses Python, which has an ORM built in, if you talk about GoLang it also has GORM, if you talk about .NET also has Entity framework, if you use Nodejs or any Javascript runtime you have a lot of options like Drizzle, Prisma and Sequlize.

Mainly, you use this technique in between, and you say Hey, technique, this is my object. Save that in a database, and it's done.

That's how they do it. So they write all the queries for you. Behind the scenes, if you check, they create a select query. So if you say, "Hey ORM, I have this roll number and can you give me the data for it?" basically, we use some, let's say, GET methods. In this case, it will fire a SELECT query. When you say save, it will fire an INSERT query. When you say the data is already there, it will fire the UPDATE query. And what if you say you want to delete? It will fire the DELETE query. So everything will be done by your ORM technique.
Image description

Basically, this is happening behind the scenes,

The term “Relational” in ORM refers to the Relational Table in the Database. The database can be SQL, MySQL, PostgreSQL, etc. The term “Object” refers to the Object of a class. And finally, the term “Mapping” refers to the mapping between these two.
Image description
It maps the fields from the Student class to the columns of the Student Table.

For example, the ID from the student class is directly mapped to the ID column from the student table. So we can directly create objects of the student class and store them in a student database table. Basically, we don’t have to write SQL statements to insert the record into the student’s table. We can use ORM to directly map objects to the relational database table.

Pros of Using ORM:

  • One of the significant advantages is the time saved for programmers.

  • ORM techniques handle query generation, reducing manual SQL coding.

  • You write less code when using ORM techniques than with SQL.

  • ORM techniques are built to eliminate the possibility of SQL injection attacks.

Cons of Using ORM:

  • Complexity Limitations: As projects become more complex, some ORM techniques may lack features for executing complex tasks. Customised queries might be necessary.

  • Performance Debate: There's an ongoing debate about the impact on application speed. ORM might slow down the application slightly, especially when compared to manually optimised SQL queries. However, the difference might just be a fraction of a second. But when we talk about scale, those seconds matter a lot.

  • Debatable Speed: While ORM aids faster development, there's a debate on whether it slows down runtime performance. In performance tests, the difference is often minimal but may be noticeable in milliseconds.

  • Customised Queries: ORM allows for customised queries. In Java, for instance, JPA supports JPQL or HQL, resembling SQL but adapted for object-oriented structures.

  • Developer Experience: If you're experienced in writing optimised SQL queries, using ORM might seem less efficient. ORM techniques have their query-building methods, which may not align perfectly with manual optimisation.

Why ORMs Are (Supposedly) Your New Best Friend

  1. You Don’t Have to Speak SQL All Day
    Look, SQL is great if you enjoy typing the same mind-numbing queries until your soul leaves your body. ORMs let you talk to your database in your own programming language—no more ancient incantations required. Just ask for what you want, and the ORM will fetch it (usually).

  2. Faster to Build Stuff (Allegedly)
    Because you’re not wrestling with SQL every five minutes, you can actually build features. More time for actually building features, less time questioning your life choices at 3 AM because you misplaced a semicolon. Progress!

  3. Makes Your Code Look Neater
    ORMs keep your code looking like a well-organised closet, instead of a pile of SQL socks thrown everywhere. When you revisit your project after a month, you might even remember what you were doing. Miracles do happen.

But Wait... Here Comes the Fun Part

  1. Sometimes It’s Slower Than You’d Like
    ORMs are like that friend who insists on taking the scenic route to the grocery store. Sure, you’ll get there eventually, but I hope you weren’t in a hurry. If your app gets popular (hey, aim high), be prepared for some performance “surprises.”

  2. Magic Can Be Annoying
    ORMS do a lot for you automatically, which is awesome—until it’s not. It’s like having a helpful roommate who does your dishes but somehow breaks your microwave in the process. Thanks, I guess?

  3. Not Great for Fancy Database Tricks
    ORMs look at your complex SQL requirements like a teenager asked to do calculus. Sure, they’ll try, but you’ll probably end up doing it yourself anyway. Sometimes, you just have to roll up your sleeves and write the SQL by hand, like a real adult.

  4. Performance Issues

  • The N+1 Query Disaster:
    You load 100 users and want their posts. Naive ORM code hits the database 101 times (1 for users, 100 for each user's posts). Your app crawls like it's running on a potato. This happens ALL THE TIME to developers who don't understand what their ORM is doing.

  • Lazy Loading Death Spiral:
    ORMs love lazy loading - sounds efficient, right? Wrong. Access one related field outside your main query context, and boom - another database hit. Do this in a loop and watch your response times explode.

  • Query Generation Stupidity:
    ORMs generate SQL that would make a DBA cry. They often SELECT * everything instead of just the fields you need, create unnecessarily complex joins, and miss obvious optimisation opportunities that any human would catch.

  • Memory Bloat:
    ORMs load entire objects when you might just need one field. Want just user emails? Too bad, here's the full user object with profile pictures, settings, and everything else eating your RAM.

    1. The "It Works on My Machine" Problem:
    2. Your ORM query runs fine with 100 records in development. Deploy with 100,000 records, and suddenly everything times out. ORMs make it easy to write code that doesn't scale.

These aren't "microsecond differences" - they're "why is our app taking 10 seconds to load" disasters that kill user experience and cost companies real money.

That's the performance reality most ORM tutorials conveniently skip.

So, Should You Use an ORM?

If you’re new and want to build stuff fast without selling your soul to SQL, ORMs can be a lifesaver. Just remember: sometimes you’ll have to peek behind the curtain and deal with the mess. ORMs are like autocorrect—incredibly helpful until they decide you meant “duck” when you clearly typed something else entirely.

By now, you must have had a clear idea of ORM. However, understanding ORM on a theoretical level is just the first step. To know the practical aspects of working with ORM, you can try working with it by using it in some of your projects.

Liked the content? Let’s connect on LinkedIn— I post more stuff like this (and would love to see what you’re building too).

Top comments (0)