1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

3GiBのJSONパース:ピークメモリ 1.17MiB RSS の実証

1
Posted at

こんにちは。トルコでデータエンジニアをしているArdaです。よろしくお願いします。

はじめに

JSONファイルのパースは、データエンジニアにとって毎日の基本的なタスクだと思います。しかし、このシンプルな作業は、見た目以上に難しい部分があります。大きなファイルがあるため、メモリ管理はとても大切です。この記事では、3GiBのJSONファイルを使って、メモリの挙動を検証します。

ストリーミング vs オンメモリ(2つのアプローチ)

1つ目のアプローチは、JSONファイルをすべてメモリに読み込む方法です。この方法は実装が一番簡単ですが、大きなファイルでは処理速度やメモリ効率が低下します。

2つ目のアプローチは、データを少しずつ読み込む「ストリーミング」です。一見すると実装が難しそうに見えますが、実際はそうではありません。Pythonではコードを1行変えるだけで、Rustでも標準的な仕組み(BufReaderなど)を使うだけで実装できます。

検証環境

  • Python: 3.13

    • msgspec: 0.21.1
    • psutil: 7.2.2
    • json: 標準ライブラリ
  • Rust: 1.92

    • serde_json: 1.0.150
    • serde: 1.0.228
  • Mac M4 Air (10 CPU, 32 GiB RAM)

使用したデータ構造

このベンチマークのデータは、Pythonのスクリプトで生成した3GiBのファイルです。ファイル形式は NDJSON(Newline-Delimited JSON) です。各行(レコード)のスキーマは以下の通りです。

JSON例

{
  "event_id": 1,
  "user_id": 9714,
  "timestamp": "2026-05-05T11:15:35.839893+00:00",
  "amount": 97592.37860093212,
  "currency": "JPY",
  "is_refunded": false,
  "note": "ndPMLcUmWYPCsrDKZL qgDMTWlymdtUJmyxjTEscMYqRSXHDNfhyJRDjQBNlGpRCFxSULjcoZOBpjJWwUpFmqsfOrbypMqEDyHyAKrhQrPfeESByxSHStbcpvItWFQYOBljtvGmJ  ulrKeBfXZWkuapRdvDHoFlqCASqaUznXMJrtdtySOVRogwJwAtNfYlWLvrPKiJ",
  "device": { "os": "android", "version": "1.0.2" },
  "tags": ["ios", "landing"]
}
データの生成 (Data Generation) スクリプト
import random
import string
import time
from datetime import datetime, timedelta, timezone
from typing import List, Optional

import msgspec


class Device(msgspec.Struct):
    os: str
    version: str


class UserEvent(msgspec.Struct):
    event_id: int
    user_id: int
    timestamp: str
    amount: float
    currency: str
    is_refunded: bool
    note: Optional[str]
    device: Device
    tags: List[str]


def random_note() -> Optional[str]:
    if random.random() < 0.3:
        return None
    length = random.randint(10, 200)
    return "".join(random.choices(string.ascii_letters + " ", k=length))


_BASE = datetime.now(timezone.utc)


def random_timestamp() -> str:
    offset = random.uniform(0, 30 * 24 * 3600)
    return (_BASE - timedelta(seconds=offset)).isoformat()


def generate_events(count: int):
    platforms = ["ios", "android", "web", "desktop"]
    versions = ["1.0.1", "1.0.2", "1.0.3", "1.0.4", "1.0.5"]
    currencies = ["TRY", "EUR", "USD", "JPY"]
    funnel_pages = ["landing", "search", "payment", "thank-you"]
    for i in range(count):
        yield UserEvent(
            event_id=i,
            user_id=random.randint(10, 50000),
            timestamp=random_timestamp(),
            amount=random.uniform(1.0, 100_000.0),
            currency=random.choice(currencies),
            is_refunded=random.choice([True, False]),
            note=random_note(),
            device=Device(os=random.choice(platforms), version=random.choice(versions)),
            tags=[random.choice(platforms), random.choice(funnel_pages)],
        )


start = time.perf_counter()
with open("../static/output.ndjson", "wb") as f:
    for event in generate_events(10_000_000):
        f.write(msgspec.json.encode(event))
        f.write(b"\n")
end = time.perf_counter()
print(f"10 mil NDJSON written in {end - start:.4f} seconds")

実装

1. オンメモリアプローチ

まずは、ファイル全体を一度に保持するオンメモリアプローチのコードです。

Python
import json
import time
start = time.perf_counter()
with open("../static/output.ndjson") as f:
    data = [json.loads(line) for line in f]
total = sum(d["amount"] for d in data)
end = time.perf_counter()
print(f"records: {len(data)}, total: {total:.2f}")
print(f"elapsed: {end - start:.4f}s")
Rust
use serde::Deserialize;
use serde_json;
use serde_json::Error;
use std::fs;
use std::time::Instant;

#[derive(Deserialize, Debug)]
struct Device {
    os: String,
    version: String,
}

#[derive(Deserialize, Debug)]
struct UserEvent {
    event_id: i32,
    user_id: i32,
    timestamp: String,
    amount: f64,
    currency: String,
    is_refunded: bool,
    note: Option<String>,
    device: Device,
    tags: Vec<String>
}

fn main() {
    let start = Instant::now();
    let content = fs::read_to_string("../static/output.ndjson")
        .expect("Should have been able to read the file");

    let mut results: Vec<Result<UserEvent, Error>> = Vec::new();
    let mut _sum: f64 = 0.0;

    for row in content.lines() {
        if let Ok(event) = serde_json::from_str::<UserEvent>(row) {
            _sum += event.amount;
            results.push(Ok(event));
        }
    }

    let duration = start.elapsed();
    println!("records: {}, total: {:.2}", results.len(), _sum);
    println!("elapsed: {:.4}s", duration.as_secs_f64());
}

2. ストリーミングアプローチ

次に、メモリ消費を抑えてデータを1行ずつ処理するストリーミングアプローチのコードです。

Python
import json
import time
start = time.perf_counter()
total = 0.0
count = 0
with open("../static/output.ndjson") as f:
    for line in f:
        obj = json.loads(line)
        total += obj["amount"]
        count += 1
end = time.perf_counter()
print(f"records: {count}, total: {total:.2f}")
print(f"elapsed: {end - start:.4f}s")

Rust
use serde::Deserialize;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::time::Instant;

#[derive(Deserialize, Debug)]
struct Device {
    os: String,
    version: String,
}

#[derive(Deserialize, Debug)]
struct UserEvent {
    event_id: i32,
    user_id: i32,
    timestamp: String,
    amount: f64,
    currency: String,
    is_refunded: bool,
    note: Option<String>,
    device: Device,
    tags: Vec<String>
}

fn main() {
    let start = Instant::now();
    let file =
        File::open("../static/output.ndjson").expect("Should have been able to read the file");
    let mut reader = BufReader::new(file);
    let mut read_str = String::new();

    let mut _sum: f64 = 0.0;
    let mut _count: i32 = 0;

    while reader.read_line(&mut read_str).unwrap() > 0 {
        if let Ok(event) = serde_json::from_str::<UserEvent>(&read_str) {
            _sum += event.amount;
            _count += 1;
        }
        read_str.clear();
    }

    let duration = start.elapsed();
    println!("records: {}, total: {:.2}", _count, _sum);
    println!("elapsed: {:.4}s", duration.as_secs_f64());
}

メトリクス & パフォーマンス

1. オンメモリアプローチ

benchmark_naive_comparison.png

Pythonコードは42.2秒、Rustコードは3.56秒で処理が終わりました。速度はRustのほうがPythonより圧倒的に速いです。

しかし、オンメモリアプローチでは両方の言語でメモリ使用量が非常に高くなります。ピークRSSが16GiBや6GiBに達するのは大きな問題です。やはり、ストリーミングなどの最適化が必要です。

2. ストリーミングアプローチ

benchmark_streaming_efficiency.png
ストリーミングでは、Pythonコードは14.19秒(66.3%減少)、Rustコードは3.61秒(ほとんど変わりません)で処理が終わりました。

一方で、ピークRSSはPythonで17.28MiB(99.8%減少)、Rustで1.17MiB(99.9%減少)まで劇的に低下しました

なぜこの差が生まれるのか?

オンメモリとストリーミングでは、パフォーマンスとメモリの動きに大きな違いがあります。その理由を分析します。

  • オンメモリアプローチの分析

    • オブジェクトのオーバーヘッド(PyObject)
      • オンメモリで巨大なファイルを読み込む際、メモリ消費量は元のファイルサイズ(3GiB)を大きく上回ります。特にPythonはRustの約3倍のメモリ(16GiB vs 6GiB)を消費しました。
      • Pythonのデータ型はすべてオブジェクトです。そのため、メタデータが多くてメモリが大きくなります。これをオブジェクトのオーバーヘッドと言います。
      • Rustは構造体(Struct)に直接データを入れるので、メモリ効率が良いです。
    • ガベージコレクション(GC)の挙動
      • メモリ消費のグラフの推移にも両言語の特徴が現れています。
      • Rustにはガベージコレクション(GC)がありません。スコープが終わるまでメモリを解放しないので、メモリグラフはまっすぐ上に上がります。
      • 一方で、Pythonはリファレンスカウントを使ってメモリを管理します。オブジェクトの参照がゼロになった瞬間にメモリが解放されるため、メモリグラフは上がったり下がったりします。一方、循環参照を検出するGCも定期的に動きます。これらのメモリ管理処理が、ランタイムのオーバーヘッドとして処理速度に影響します。
  • ストリーミングアプローチの分析

    • メモリ領域の再利用
      • ストリーミングを使うことで、両言語ともメモリ消費量を劇的に抑えることができました。
      • ストリーミングでは、1行を処理するたびに、そのオブジェクトはすぐに不要になります。Pythonではリファレンスカウントによってすぐに解放され、Rustでは read_str.clear() でバッファを再利用しています。どちらも結果的にメモリ使用量が一定に保たれます。
    • インタプリタとネイティブコードの「16MiB」の差
      • ストリーミングの時、PythonとRustの間に約16MiBの差があります(17.28MiB vs 1.17MiB)。
      • Rustはコンパイルされたコードなので、ランタイムのオーバーヘッドがありません。
      • しかし、Pythonはインタプリタ言語なので、CPythonインタプリタ自体の起動オーバーヘッドがあります。

まとめ

  • メモリ効率で一番大切なのは「言語」より「アプローチ」だと思います。ストリーミングとオンメモリの差はとても大きいです。PythonとRustの言語の差より、ずっと大きいです。
  • 大きなファイルを読むとき、まずストリーミングを使ったほうがいいです。
  • スピードや少ないメモリが必要なとき、Rustのほうがいいです。でも、簡単なジョブやプロトタイプなら、Pythonのストリーミングで大丈夫です。

ご質問やアドバイスがあれば、ぜひコメントをお願いします!最後まで読んでいただき、ありがとうございました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?