DEV Community


Posted on • Updated on


Compare rust vs nodejs script runtime

Hello my folks
Nice to see your eye[s] :)
I am graduate at communication engineer, now for near 2 years I am Nodejs and Python developer. Recently I had a thought that is If I learn a low level language among a those high level languages, may help me to extend my insight to computer science. SO I started to learn Rust.
In one of my nodejs program, I read a file include 5131 hexadecimal string and convert them to binary, then the bin number split to 5 separate bin noms and convert each one to decimal.

No for my first rust program, I implement this with rust and compare the runtime of bot javascript and rust program.

this is the rust program:

use std::fs;
use to_binary::BinaryString;

pub struct ParsedEpc {
    pub header: u64,
    pub partition: u64,
    pub filter: u64,
    pub item_number: u64,
    pub serial_number: u64,
    pub company_name: u64,

fn main() {
    let contents = fs::read_to_string("splitted.txt")
        .expect("Wrong to read from file")
        .replace("\"", "");
    let splitted: Vec<&str> = contents.split(",").collect();

    println!("{} epcs found", splitted.len());

    for epc in splitted {

fn parse_data(epc: &str) -> ParsedEpc {
    let decoded_str = BinaryString::from_hex(epc).unwrap().to_string();
    let radix: u32 = 2;
    ParsedEpc {
        header: u64::from_str_radix(&decoded_str[0..8], radix).unwrap(),
        partition: u64::from_str_radix(&decoded_str[8..11], radix).unwrap(),
        filter: u64::from_str_radix(&decoded_str[11..14], radix).unwrap(),
        company_name: u64::from_str_radix(&decoded_str[14..26], radix).unwrap(),
        item_number: u64::from_str_radix(&decoded_str[26..58], radix).unwrap(),
        serial_number: u64::from_str_radix(&decoded_str[58..], radix).unwrap(),
Enter fullscreen mode Exit fullscreen mode

this is the js program:

const fs = require('fs');

fs.readFile('splitted.txt',"utf-8", (err, data) => {
  if(err) throw err;

  const epcList = data.split(",");

  console.log(epcList.length,"epcs found");

  epcList.forEach(epc => {

function parseEpc(epc) {
  const bin = parseInt(epc, 16).toString(2);
  return {
      header: parseInt(bin.slice(0, 8), 2).toString(10),
      partition: parseInt(bin.slice(8, 11), 2).toString(10),
      filter: parseInt(bin.slice(11,14), 2).toString(10),
      itemNumber: parseInt(bin.slice(14, 26), 2).toString(10),
      serialNumber: parseInt(bin.slice(26, 58), 2).toString(10),
      companyName: parseInt(bin.slice(58), 2).toString(10),
Enter fullscreen mode Exit fullscreen mode

this is the runtime result:

Image description

the rust is faster about 4x.
That is so interesting for me to create a lib in rust and use them in nodejs program.

Top comments (0)

⚡️⛓JavaScript Visualized: Scope

async await

☝️ Check out this all-time classic DEV post