DEV Community

Cover image for Ruby VS Python VS C++ VS JavaScript
Samuel Grasse-Haroldsen
Samuel Grasse-Haroldsen

Posted on • Updated on

Ruby VS Python VS C++ VS JavaScript

Why Ruby?

When I initially started learning Ruby, I read a lot of articles talking about the problems with Ruby. "It's a dead language." "Nobody uses Ruby anymore." "Just learn Python. It's faster anyways." While these comments didn't hinder me at all, they did make me question the reason for learning Ruby: why didn't my bootcamp choose a faster more popular language that was still beginner friendly like Python? Needless to say, I still attended the bootcamp and learned Ruby, and I am so happy I did.

In The Beginning There Was C, + More

Although I never graduated university (life has a habit of getting busy), I did work towards a software engineering degree. My university, I'm sure like many others', introduced programming with one of the more unforgiving languages, C++. I remember not even worrying about the language: I didn't know the difference between compiled and interpreted languages. Weird syntax? Yeah, that's just programming. Things got difficult when I started my second semester computer science course. We were writing games and dynamic memory allocation didn't come naturally to me.

Bootcamp

After I dropped out I spent some time learning HTML, CSS, and then JavaScript. Thankfully, JavaScript has a lot of similarities with C++ when it comes to syntax. Sure types aren't a thing (I know they can be #TypeScript), but I felt fine with the loops and conditional statements, and I sure do love semicolons. In 2020 I decided to take a leap of faith and applied for Flatiron School's software engineering program. The curriculum would include JavaScript, Ruby, React, and Rails. I was very excited to learn how to build real-world applications. My first project was using an API to make a CLI application, and it was so great to finally understand what an API was.

The Saving Gem

When I started learning Ruby, I didn't think much of the differences between it, JavaScript or C++. Sure, ending blocks of code instead of using curly brackets was strange and leaving out parentheses was not something I did. Honestly, I still coded very much in the C++ way my university taught me: for/while loops, the parentheses, etc. But then something wonderful happened. I learned about enumerables. A beautiful chord was struck. I could easily alter data with a few simple lines of code. I could check if every element in an array was even with .all?. I could easily see if I had a user with the name Voltron with .any?. I could even change every element in an array to the same thing with .collect. I started to the see the beauty of doing things the Ruby way.

The Epiphany

After diving deep into JavaScript and learning about higher-order functions, I realized other languages could do similar things to Ruby. .forEach and .map for .each and .map. Even after realizing this I still felt Ruby was more magical. Maybe I felt this way because I could simply express what I wanted the computer to do with fewer lines of code. Maybe Ruby was my first real language. Regardless of why, I was a Rubyist.

Again... Why Ruby?

Fast forward to present day post graduation: the job search. Searching for and applying to jobs for months I have realized that while definitely not a dead language and still highly in demand, Ruby is not the most sought after language. And most of the time teams that are looking for Ruby/Rails devs are looking for senior engineers. I needed to adapt and broaden my skills. I decided that while I would continue perfecting my Ruby skills and make apps with Rails and JavaScript, I would also learn a new language: Python.

Easy Right?

I made this decision mostly based on the fact that I have seen Python used in multiple FOSS project, and I had heard it was easy to automate tasks using the language. I started learning using "Automate the Boring Stuff". I hadn't gotten very far in when I decided that Python wasn't right for me. Too many colons, no visual ending to block of code besides the lack of white space, and don't get me started on needing to type exit() vs just exit in the Python Interpreter. Ruby had spoiled me. In my moment of contempt for such a foul looking language I decided to see if Python was indeed faster than Ruby! Surely Ruby 3.0.0 would give the "two snakes" a run for their money.

The Race

Initially I wanted to see how fast the languages could loop through a range and do some calculations while printing the answers. Interestingly enough I learned that Ruby's print is much faster than its puts and Python's print() beats Ruby's puts but not its print (I threw in JavaScript and yikes console.log is really really slow). Printing probably isn't a good indicator of anything, so I decided I needed some random number generation and some conditional statement to execute on a large range of numbers multiple times. Here's the finished solution in both languages plus JavaScript and C++ just for fun:

Ruby

def do_the_thing(num)
  success = []
  no_success = []
  while num > 0
    if rand(num) >= num - 10
      success.push(num)
    else
      no_success.push(num)
    end
    num -= 1
  end
  return success.size
end
sum = 0
100.times do
  sum += do_the_thing(1000000)
end
puts sum
Enter fullscreen mode Exit fullscreen mode

Python

import random
def do_the_thing(num):
    success = []
    no_success = []
    while num > 0:
        if random.randint(1, num) >= num - 10:
            success.append(num)
        else:
            no_success.append(num)
        num -= 1
    return len(success)
sum = 0
for x in range(1, 100):
    sum += do_the_thing(1000000)
print(sum)
Enter fullscreen mode Exit fullscreen mode

C++

#include <iostream>
#include <vector>
#include <ctime>
using namespace std;

int doTheThing(int num)
{
    srand(time(NULL));
    vector < int > success;
    vector < int > noSuccess;
    while(num > 0) 
    {
        if((rand() % num + 1) >= num - 10)
        {
            success.push_back(num);
        }
        else
        {
            noSuccess.push_back(num);
        }
        num--;
    }
    return success.size();
}

int main()
{
    int sum = 0;
    for(int i = 0; i <= 100; i++)
    {
        sum += doTheThing(1000000);
    }
    cout << sum << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript

function doTheThing(num) {
    let success = [];
    let noSuccess = [];
    while (num > 0) {
        if((Math.floor(Math.random() * Math.floor(num))) >= num - 10) {
            success.push(num);
        } else {
            noSuccess.push(num);
        }
        num -= 1;
    }
    return success.length;
}

let sum = 0;
for(let i = 0; i <= 100; i++) {
    sum += doTheThing(1000000);
}
console.log(sum)
Enter fullscreen mode Exit fullscreen mode

The Results

Thanks to Linux's time command, I was able to time how long a given command would take (I used node for the JS and I combined the compilation time and run time for C++).

language real time command
ruby 0m21.568s time ruby random.rb
python 1m34.050s time python3 rand.py
js 0m04.290s time node random.js
c++ 0m03.527s time g++ random.cpp + time a.out

JavaScript definitely surprised me the most with how speedy quick it was, and I didn't think Python would be as slow as it was. It might have something to do with including that random module (I had to change the name of the file to rand because the interpreter didn't like the file having the same name as the module).

The Real Results

Ultimately I know every programming language has its pros and cons and obviously generating a random number isn't the best benchmark for a language. But I definitely had fun writing the same code in 4 different languages and writing C++ was an especially exciting trip down memory lane. It's fun knowing that each language has it's own quirks and seeing C++ after learning Ruby and JS and a little bit of Python was very eye-opening. I highly recommend learning another language once you've got your first one down solid. You will learn different ways of doing things and if one thing is certain it is that we should always be learning in this industry!

Top comments (1)

Collapse
 
juancarlospaco profile image
Juan Carlos

Interesting post, Ruby 3 is JIT now,
but I read some post saying is really not faster for bigger projects.

Heres my solution and time, Nim lang code,
looks similar to Python or Ruby, runs like C or C++,
Nim compiles to JavaScript too (like TypeScript),
uses automatic deterministic compile-time memory management.

import random

proc do_the_thing(n: static int): int {.noinit, inline.} =
  var num = n  # Function arguments are immutable by default.
  var success, no_success = newSeqOfCap[int](num)
  while num > 0:
    if rand(1..num) >= num - 10:
      success.add num
    else:
      no_success.add num
    dec num  # Same as  num = num - 1
  result = success.len  # same as  result = success.len; return result

var sum = 0
for _ in 1..100:
  sum += do_the_thing(1000000)

echo sum
Enter fullscreen mode Exit fullscreen mode

Linux time says:

real    0m3,030s
user    0m3,030s
sys     0m0,010s
Enter fullscreen mode Exit fullscreen mode

🙂👍