json_encode 比 PHP 中的 Avro 编码器更快(基准测试)

问题描述 投票:0回答:1

所以我一直在阅读有关 Avro 编码如何比 JSON 更快的内容,但是当我运行自己的测试时,我得到了完全不同的结果。在我的测试中,没有什么异常,JSON 始终比 Avro 快得多。我在这里错过了什么吗?

这是 Avro 的序列化方法:

public function serialize(array $documentArray)
    {
        $this->schemaID = 1;
        $parsedSchema = AvroSchema::parse(SCHEMA);

        // check if there's already an io datum writer in the local cache, if so use it
        if (isset($this->ioDatumWriterCache[$this->schemaID])) {
            $datumWriter = $this->ioDatumWriterCache[$this->schemaID];
        } else {
            $datumWriter = new \AvroIODatumWriter($parsedSchema);
            $this->ioDatumWriterCache[$this->schemaID] = $datumWriter;
        }

        // check if there's already a binary encoder in the local cache, if so use it
        if (isset($this->binaryEncoderCache[$this->schemaID])) {
            $encoder = $this->binaryEncoderCache[$this->schemaID];
        } else {
            $encoder = new \AvroIOBinaryEncoder($this->ioWriter);
            $this->binaryEncoderCache[$this->schemaID] = $encoder;
        }

        $datumWriter->write($documentArray, $encoder);

        return $this->ioWriter->string();
    }

这是 JSON 的:

public function serialize(array $documentArray): string
    {
        try {
            return json_encode($documentArray, JSON_THROW_ON_ERROR);
        } catch (\Exception $ex) {
            throw new ObjectIOException('JSON decode exception', 0, $ex);
        }
    }

我正在使用 phpbench 来运行基准测试。

结果(为两者序列化同一组数据)是:

JSON 编码平均时间: 1.685μs 1.642μs 1.637μs 1.642μs 1.637μs

Avro 编码平均时间: 40.574μs 40.716μs 40.664μs 40.480μs 40.583μs

php json avro benchmarking jsonencoder
1个回答
0
投票

您使用的语言和您正在序列化的数据会产生影响。

每次序列化时,您的代码都会系统地解析架构!这是必要的吗?

PHP中的json_encode是一个语言库函数,速度非常快。 Avro 代码是一个 PHP 库(速度没有那么快)。

什么是文档数组?将整数、双精度数...转换为 JSON 字符串所花费的时间不可忽略。另一方面,将 JSON 字符串转换回整数和双精度数的时间也不容忽视。

在大多数编译语言中,Avro 序列化可能比 JSON 更快。它总是更紧凑。

© www.soinside.com 2019 - 2024. All rights reserved.