Rust program slower than expected

⚓ rust    📅 2025-05-09    👤 surdeus    👁️ 2      

surdeus

Hi, I am a complete newbie with Rust, just playing with it.
I tried to create a simple program just to get a feeling of the language and compare it to others.
At my first attempt I'm not getting the expected speed so I'm puzzled if I'm doing something wrong?
The release-compiled version runs a little slower than a PHP script that does the same thing.
Rust: 0m2.071s. PHP: 0m1.770s.

The program just de/serializes an incrementally growing JSON.

use serde_json::{Map, Value, json};

fn main() {
    println!("Wait...");
    let mut last = r#"
    {
        "counter": 0
    }"#
    .to_string();
    for _i in 0..3000 {
        let mut x: Map<String, Value> = serde_json::from_str(last.as_str()).unwrap();
        let counter = x["counter"].to_string();
        let mut node = &mut x;
        for key in counter.chars() {
            if !node.contains_key(&key.to_string()) {
                node.insert(key.to_string(), Value::from(serde_json::Map::new()));
            }
            node = node
                .get_mut(&key.to_string())
                .unwrap()
                .as_object_mut()
                .unwrap();
        }
        x["counter"] = Value::from(x["counter"].as_i64().unwrap() + 1);
        let next = json!(x);
        last = next.to_string();
    }
    println!("{}", last.len());
}

Here's the PHP version:

<?php

echo 'Wait...' . PHP_EOL;
$last = '
    {
		"counter": 0
    }';
for( $i = 0; $i < 3000; $i++ ) {
	$x = json_decode( $last );
	$node = &$x;
	foreach( str_split( $x->counter ) as $key ) {
		$node->$key ??= new stdClass();
		$node = &$node->$key;
	}
	$x->counter++;
	$last = json_encode( $x );
}
echo strlen( $last ) . PHP_EOL;

5 posts - 3 participants

Read full topic

🏷️ rust_feed