Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 10, 2023 07:55 pm GMT

The Great Prime Number Challenge: Which Programming Language is the Fastest?

Setup

To have a hands on experience of different speeds between different programming languages, I decided to see how fast different languages would calculate and store the prime numbers between 1 and 10,000,000. The seven languages I choose are:

  • C
  • Go
  • Java
  • JavaScript
  • Python
  • Ruby
  • Rust

To set this up, I first wrote the following python code:

import mathfrom datetime import datetimedef is_prime(num):    if num < 2:        return False    for i in range(2, int(math.sqrt(num)) + 1):        if num % i == 0:            return False    return Truestart = datetime.now()primes = []for num in range(int(1e7)):    if is_prime(num):        primes.append(num)print('Python: ', datetime.now() - start)

The code determines whether an integer n is prime or not by checking if any of the integers in the range [2, sqrt(n)] has a quotient with a zero remainder. Then, it iterates through the integers in the range [1, 10,000,000], storing the integer if it is indeed prime.

Although I'm not interested in viewing or using the list of prime numbers, it is import to store the information so that the language's memory management is tested.

Then, using ChatGPT, I converted this Python code into the other 6 languages.

C:

#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#include <math.h>#include <time.h>bool is_prime(int num) {    if (num < 2) {        return false;    }    for (int i = 2; i <= sqrt(num); i++) {        if (num % i == 0) {            return false;        }    }    return true;}int main() {    clock_t start = clock();    int *primes = malloc(10000000 * sizeof(int));    int count = 0;    for (int num = 2; num < 10000000; num++) { // Start at num=2, not num=0        if (is_prime(num)) {            primes[count++] = num;        }    }    printf("C: %f seconds
", ((double)clock() - start) / CLOCKS_PER_SEC); free(primes); // Free the dynamically allocated memory return 0;}

Go:

package mainimport (    "fmt"    "math"    "time")func isPrime(num int) bool {    if num < 2 {        return false    }    for i := 2; i <= int(math.Sqrt(float64(num))); i++ {        if num%i == 0 {            return false        }    }    return true}func main() {    start := time.Now()    primes := []int{}    for num := 0; num < int(1e7); num++ {        if isPrime(num) {            primes = append(primes, num)        }    }    fmt.Println("Go: ", time.Since(start))}

Java:

import java.time.Duration;import java.time.Instant;import java.lang.Math;import java.util.ArrayList;import java.util.List;public class primes {    public static boolean isPrime(int num) {        if (num < 2) {            return false;        }        for (int i = 2; i <= Math.sqrt(num); i++) {            if (num % i == 0) {                return false;            }        }        return true;    }    public static void main(String[] args) {        Instant start = Instant.now();        List<Integer> primes = new ArrayList<Integer>();        for (int num = 0; num < 10000000; num++) {            if (isPrime(num)) {                primes.add(num);            }        }        System.out.println("Java: " + Duration.between(start, Instant.now()).toMillis() + " ms");    }} 

JavaScript:

function isPrime(num) {    if (num < 2) {      return false;    }    for (let i = 2; i <= Math.sqrt(num); i++) {      if (num % i === 0) {        return false;      }    }    return true;  }  const start = new Date();  const primes = [];  for (let num = 0; num < 1e7; num++) {    if (isPrime(num)) {      primes.push(num);    }  }  console.log(`JavaScript: ${(new Date() - start)/1000} seconds`);

Ruby:

def is_prime(num)    return false if num < 2    (2..Math.sqrt(num).to_i).each do |i|      return false if num % i == 0    end    true  end  start = Time.now  primes = []  (0...1e7.to_i).each do |num|    primes << num if is_prime(num)  end  puts "Ruby: #{Time.now - start} seconds"

Rust:

use std::time::{Instant, Duration};use std::f64::consts::SQRT_2;fn is_prime(num: u32) -> bool {    if num < 2 {        return false;    }    for i in 2..=((num as f64).sqrt() as u32) {        if num % i == 0 {            return false;        }    }    true}fn main() {    let start = Instant::now();    let mut primes = Vec::new();    for num in 0..10_000_000 {        if is_prime(num) {            primes.push(num);        }    }    let end = Instant::now();    let time_elapsed = end - start;    println!("Rust: {:?}", time_elapsed);}

Results

LanguageRace 1Race 2Race 3Average
C8.9s8.9s8.9s8.9s
Go11.8s11.6s11.6s11.7s
Java4.6s4.7s4.6s4.6s
JavaScript4.4s4.4s4.4s4.4s
Python99.5s88.9s88.2s92.2s
Ruby64.4s68.6s64.4s65.8s
Rust25.2s25.3s25.3s25.3s

Winner: JavaScript

Slowest: Python (20x slower than JavaScript)

Discussion

What can we conclude from this test? Well, what we can't conclude is that JavaScript is twice as fast as C, nor that Python is 10x slower than C. We can deduce that for calculating prime numbers in this way, Java and JavaScript would be excellent choices with regards to speed and Python and Ruby would be relatively poor choices. It is important to note that this was just testing one application of these languages, and does not give a clear picture to the overall efficiency of the language. Clearly, Python and Ruby are significantly slower than Java/JavaScript/C, so it may be safe to assume that these languages are slower in general. Indeed, one of Python's biggest criticisms and reasons it is not used is that it is slow.

An important factor in the discussion of language speed is static typing versus dynamic typing. In short, static typing means that the type of a variable is checked at compile-time, and dynamic typing means that the type of a variable is checked at run-time. The languages tested that are statically typed are C, Go, Java, and Rust, where JavaScript, Python, and Ruby are dynamically typed.

Why is JavaScript so much faster than the other two dynamically typed languages? While there are factors other than typing that affect speed, this difference is largely due to a concept called Just-In-Time (JIT) Compilation link. It is partly because JavaScript is so widely used and popular that the large community has developed this and other features of JavaScript that help speed it up.


Original Link: https://dev.to/kschneider0/the-great-prime-number-challenge-which-programming-language-is-the-fastest-2hdo

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To