I am perplexed by the lack of significant performance variation between JS and Go in my specific situation

After working on the Project Euler problem #12, focusing on divisors and triangle numbers, I successfully solved it using both Go and JavaScript. Surprisingly, despite my assumption that the Go code would be much faster due to its building process compared to the runtime execution of JS, there were situations where the JS code outperformed the Go code.

Here is a snippet of the code I used:

https://gist.github.com/noraesae/675e40477e177f9f63f9

The test was conducted on my MacBook, which has the following specifications:

Processor: 2.6 GHz Intel Core i5
Memory: 8 GB 1600 MHz DDR3

I executed the code with the following commands:

$ #js
$ node euler12.js

$ #go
$ go build euler12.go
$ ./euler12

I am puzzled by the fact that there was no significant difference in performance between the two languages. Could there be something wrong with my approach? If not, what could explain the lack of disparity in speed? Interestingly, when comparing Go to Python, there was a notable gap in performance. Any insights would be greatly appreciated. Thank you.

Answer №1

It's quite intriguing that, on my MacBook Pro from late 2013 with an i7 processor running at 2.3GHz, the JavaScript code outperforms the Go code:

JavaScript:

time node test.js
842161320

real    0m4.437s
user    0m4.900s
sys     0m0.150s

Go:

time GOMAXPROCS=8 ./test
842161320

real    0m7.345s
user    0m7.470s
sys     0m0.010s

However, with a swift optimization of the Go code:

Go:

time GOMAXPROCS=8 ./test
842161320

real    0m1.760s
user    0m11.610s
sys     0m0.230s

The optimization I implemented may seem simplistic: parallelize the computation process:

package main

import (
        "fmt"
        "os"
        "runtime"
)

func numberOfDivisors(n int64) int64 {
        var result int64

        var i int64 = 1
        for true {
                if n%i == 0 {
                        opposite := n / i
                        if opposite == i {
                                result++
                                return result
                        } else if opposite > i {
                                result += 2
                        } else {
                                return result
                        }
                }
                i++
        }
        return result
}

func main() {
        var acc int64
        var i int64 = 1

        maxRoutines := runtime.NumCPU()
        c := make(chan struct{}, maxRoutines)
        for i := 0; i < maxRoutines; i++ {
                c <- struct{}{}
        }
        for true {
                <-c
                acc += i
                go func(acc int64) {
                        defer func() { c <- struct{}{} }()
                        if numberOfDivisors(acc) > 1000 {
                                fmt.Println(acc)
                                os.Exit(0)
                        }
                }(acc)
                i++
        }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing a custom element as a dropdown button in React Bootstrap: A guide

I am encountering an issue with my component. I am utilizing React bootstrap, however, I need to create a button that toggles the menu on click using FontAwesomeIcon instead of a traditional button. Here is an example of my code: render() { retur ...

Retrieve information from XML using jQuery

<?xml version="1.0" encoding="UTF-8"?> <slider> <csliderData1> <title>Kung Fu Panda</title> <content>In the Valley of Peace, Po the Panda finds himself chosen as the Dragon Warrior despite</content ...

Pushing state history causes browser back and forward button failure

I'm currently utilizing jQuery to dynamically load content within a div container. On the server side, the code is set up to detect if the request is being made through AJAX or GET. In order to ensure that the browser's back and forward buttons ...

Showcasing all products via the terminal using the Mailchimp API in JavaScript

I am currently utilizing mailchimp to showcase all the email addresses from an audience. To achieve this, I have implemented the following code: const client = require("@mailchimp/mailchimp_marketing"); client.setConfig({ apiKey: "MY API KE ...

The back div is not retained on the second animation when flipping the card

In my card with a unique animation, clicking on the "Edit" button triggers the following actions: It smoothly transitions to the center of the screen. During this movement, it rotates by 180 degrees, revealing a blank green back content. Once the card r ...

Rendering a dynamic list of asynchronous components in Vue 3, with support for extension

Could you please assist me in resolving this issue? I've spent countless hours searching for a solution, but I can't seem to make it work. Vue is still very new to me. Let me provide some more context. I have an asynchronous component that i ...

Display numeric data when hovering over circles in the Google Maps API using Javascript

I recently implemented the Google Maps example code that displays a circle hovering over a city, with the size of the circle representing the population. I'm looking to enhance this feature by including numeric data display on mouseover as well. Any a ...

Issue with React hooks: Callback functions from library events (FabricJS) not receiving the updated state values

Why am I not receiving the updated state values within FabricJS events like object:modified, mouse:up, etc... even though I can set state values inside those callback functions. Upon attempting to retrieve the state value, it consistently returns the init ...

What methods do web browsers use to detect when a user has viewed a custom image on a webpage?

As I work on creating a website to sell handmade crafts, it is essential that high-quality images are displayed for each product. In order to address SEO issues, I am considering loading the images asynchronously only when the user reaches the thumbnail ...

Utilizing Rails for dynamic form validation with AJAX

As someone who is new to jQuery, AJAX, and JavaScript in general, I am facing a challenge with front-end validation for a Rails form that utilizes an ajax call to query the server. The validation works fine when I am debugging, giving enough time for the A ...

The ajax function is malfunctioning when called from an external JavaScript file

I am having an issue with a Registration page that only has UserName and Password fields. When I click on the Submit button, I want to be able to submit the new User Details using an ajax call with jQuery. I have tried defining an Insert function on butt ...

Comparing a series of smaller strings to a larger string for testing purposes

My website has an array filled with bot names. Whenever a user or bot visits the site, I retrieve the user-agent and want to check if any of the values in my array are present in it. var bots = [ "twitterbot", "linkedinbot", "facebookexternalhit", ...

The CanvasJS column chart is failing to render data from a JSON string

I am experimenting with canvas js for the first time and need assistance with a particular issue. Can you provide me with some hints on how to resolve this? Currently, I have a method in an ASP.NET ASMX web service that returns a JSON string formatted as ...

When sending multiple JSON objects in an HTTP POST request to an ASP.NET MVC controller action, they may not be properly bound

I am passing two JSON objects to an ASP.NET MVC controller action, but both parameters are showing as null. Can anyone identify the error, possibly related to incorrect naming? /* Source Unit */ var sourceParent = sourceNode.getParent(); var sourceUnitPa ...

Unable to retrieve values while mapping in next.js / react due to access restrictions

Hi there, I'm currently facing an issue with accessing specific values in a JSON object. Below is the code snippet that is causing the error: const Index = props => ( <Layout> <h1>Case Studies</h1> <ul> {props.caseS ...

What is the best way to customize a component in a view?

<template> <div class="about"> <Header /> <h1>Welcome to the dashboard page</h1> </div> </template> <script> import Header from "../components/layout/Header.vue"; export default { name: "dashb ...

Data of an object disappears when it is passed to Meteor.call

In my React/Meteor project, I encountered an issue while trying to pass an object with data from the state to a method on the server for database insertion. Surprisingly, when the object is passed from the React component to the Meteor method, one of the c ...

What are the steps to approve an Amazon Pay request for retrieving a "get checkout session"?

Exploring the integration of Amazon pay as a payment option for customers on my website has led me to encounter some challenges with understanding the request headers required for calling the Amazon Pay API. Attempting a request to 'https://pay-api.a ...

User class instantiation in livequery is initiated

Is it possible to initialize the user class in a live query? I have initialized the user class in my index.js and it shows up in my network inspector. However, when I attempt to query, nothing appears in the websocket. Below is the code showing how I init ...

Leveraging jQuery's .animate method to create engaging search box animations

Greetings esteemed individuals... I am currently working on enhancing the search component for my application... http://jsfiddle.net/SkyKOG/K8utq/24/ input{ display:none; width:0px; color:#999; } Initially, I only had a simple search box so ...