Rust vs JavaScript Performance Examples
Where Rust Shines: Image Processing
Rust would dramatically outperform JavaScript when processing large images. For example, applying a Gaussian blur filter to a high-resolution image:
use image::{ImageBuffer, Rgb};
fn gaussian_blur(img: &ImageBuffer<Rgb<u8>, Vec<u8>>, sigma: f32) -> ImageBuffer<Rgb<u8>, Vec<u8>> {
let (width, height) = img.dimensions();
let mut result = ImageBuffer::new(width, height);
// Calculate kernel size based on sigma
let kernel_size = (sigma * 3.0).ceil() as usize * 2 + 1;
let kernel_radius = kernel_size / 2;
// Generate Gaussian kernel
let mut kernel = vec![0.0; kernel_size];
let mut sum = 0.0;
for i in 0..kernel_size {
let x = i as f32 - kernel_radius as f32;
kernel[i] = (-x*x/(2.0*sigma*sigma)).exp();
sum += kernel[i];
}
// Normalize kernel
for i in 0..kernel_size {
kernel[i] /= sum;
}
// Apply horizontal blur
let mut temp = ImageBuffer::new(width, height);
for y in 0..height {
for x in 0..width {
let mut r_sum = 0.0;
let mut g_sum = 0.0;
let mut b_sum = 0.0;
for i in 0..kernel_size {
let kx = x as isize + i as isize - kernel_radius as isize;
if kx >= 0 && kx < width as isize {
let pixel = img.get_pixel(kx as u32, y);
r_sum += pixel[0] as f32 * kernel[i];
g_sum += pixel[1] as f32 * kernel[i];
b_sum += pixel[2] as f32 * kernel[i];
}
}
temp.put_pixel(x, y, Rgb([r_sum as u8, g_sum as u8, b_sum as u8]));
}
}
// Apply vertical blur
for y in 0..height {
for x in 0..width {
let mut r_sum = 0.0;
let mut g_sum = 0.0;
let mut b_sum = 0.0;
for i in 0..kernel_size {
let ky = y as isize + i as isize - kernel_radius as isize;
if ky >= 0 && ky < height as isize {
let pixel = temp.get_pixel(x, ky as u32);
r_sum += pixel[0] as f32 * kernel[i];
g_sum += pixel[1] as f32 * kernel[i];
b_sum += pixel[2] as f32 * kernel[i];
}
}
result.put_pixel(x, y, Rgb([r_sum as u8, g_sum as u8, b_sum as u8]));
}
}
result
}
This would be 10-20x faster than JavaScript because:
- Rust has no garbage collection pauses
- Direct memory access with no boxing/unboxing
- SIMD optimizations
- Predictable memory layout
- Compile-time optimizations
Web Server Case Where Rust Competes Well: JSON Parsing for API Requests
In a high-throughput API server handling JSON payloads, Rust can compete with Node.js despite V8's JIT optimizations:
use actix_web::{web, App, HttpServer, Responder};
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Serialize, Deserialize)]
struct ApiRequest {
user_id: String,
items: Vec<Item>,
metadata: Value,
}
#[derive(Serialize, Deserialize)]
struct Item {
id: u64,
quantity: u32,
price: f64,
}
#[derive(Serialize)]
struct ApiResponse {
success: bool,
total: f64,
processed_items: usize,
}
async fn process_order(req: web::Json<ApiRequest>) -> impl Responder {
// Calculate order total
let total = req.items.iter()
.map(|item| item.quantity as f64 * item.price)
.sum();
web::Json(ApiResponse {
success: true,
total,
processed_items: req.items.len(),
})
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/api/order", web::post().to(process_order))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
Rust competes well here because:
- Zero-copy JSON parsing with serde
- Predictable memory usage under load
- No GC pauses during request handling
- Efficient connection pooling
- Better handling of many concurrent connections
Would you like me to explain or break down the code?