Optimize JsonbContainerTypeName by reordering type checks

From: Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>
To: pgsql-hackers(at)lists(dot)postgresql(dot)org
Subject: Optimize JsonbContainerTypeName by reordering type checks
Date: 2025-08-26 05:26:28
Message-ID: 650638be-4766-4fb1-aa95-eb82c5a4d275@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi Hacker,

While reading jsonb related code, I found JsonbContainerTypeName() can
be optimized. The function currently checks for the less common scalar
container type before checking for objects and arrays.

This patch reorders the checks to prioritize the most common cases. The
macros JsonContainerIsArray() and JsonContainerIsObject() are simple bit
checks and are now evaluated first. This avoids the overhead of calling
the JsonbExtractScalar() function in the vast majority of use cases.

I did the following test:

```

CREATE TABLE test_jsonb_types (
    id SERIAL PRIMARY KEY,
    data JSONB
);

INSERT INTO test_jsonb_types (data) VALUES
('{"name": "Alice", "age": 30}'),
('[1, 2, "three"]'),
('"hello world"'),
('12345'),
('true'),
('null');

evantest=# SELECT id, data, jsonb_typeof(data) AS data_type FROM
test_jsonb_types;
 id |             data             | data_type
----+------------------------------+-----------
  1 | {"age": 30, "name": "Alice"} | object
  2 | [1, 2, "three"]              | array
  3 | "hello world"                | string
  4 | 12345                        | number
  5 | true                         | boolean
  6 | null                         | null
(6 rows)

```

Best regards,

--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/

Attachment Content-Type Size
v1-0001-jsonb-Optimize-JsonbContainerTypeName-by-reorderi.patch text/plain 1.5 KB

Browse pgsql-hackers by date

  From Date Subject
Next Message shveta malik 2025-08-26 05:51:05 Re: Logical Replication of sequences
Previous Message jian he 2025-08-26 04:53:07 Re: CREATE SCHEMA ... CREATE DOMAIN support