Skip to content

Instantly share code, notes, and snippets.

@reqshark
Created April 26, 2019 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reqshark/b104090c15747876da587243450e80d1 to your computer and use it in GitHub Desktop.
Save reqshark/b104090c15747876da587243450e80d1 to your computer and use it in GitHub Desktop.
why i am switching to go from javascript

promises and bloat

javascript got one thing right with callbacks. that got thrown out with promises.

error swallowing and other anonymous/bad syntax conventions

  • who cares about function declarations?
  • named functions provide an informative callstack for debugging/visibility, oops not arrows =>
  • async await is not a coroutine
  • chained promises swallow errors and are complex/unintuitive

go run

go run myprog.go is the same as node myprogram.js

perf

compared a slow fibonacci on my macbook pro

result

  • go program: Fibonacci(45) = 1134903170 in 6353ms
  • node output: Fibonacci(45) = 1134903170 in 11264ms

run

run this goroutine and you'll get a sweet spinner in the console before the fib output:

package main

import (
  "time"
  "fmt"
)

func main(){
  var then = jsDatedotnow()
  go spinner(100 * time.Millisecond)
  const n = 45
  fibN := fib(n) // slow
  fmt.Printf("\rFibonacci(%d) = %d in %dms\n", n, fibN, jsDatedotnow() - then)
}

func spinner(delay time.Duration){
  for {
    for _, r := range `-\|/` {
      fmt.Printf("\r%c", r)
      time.Sleep(delay)
    }
  }
}

func fib(x int) int {
  if x < 2 {
    return x
  }
  return fib(x-1) + fib(x-2)
}

func jsDatedotnow() int64 {
    return time.Now().UnixNano() / 1e6
}

identical result in node.js, but arrives much later while performing fewer/zero spin console/prints and simpler execution:

const then = Date.now()
const n = 45
const fibN = fib(n)

console.log("\rFibonacci(%s) = %s in %sms", n, fibN, Date.now() - then)

function fib (x){
  return x < 2 ? x : fib(x-1) + fib(x-2)
}
package main
import (
"time"
"fmt"
)
func main(){
var then = jsDatedotnow()
go spinner(100 * time.Millisecond)
const n = 45
fibN := fib(n) // slow
fmt.Printf("\rFibonacci(%d) = %d in %dms\n", n, fibN, jsDatedotnow() - then)
}
func spinner(delay time.Duration){
for {
for _, r := range `-\|/` {
fmt.Printf("\r%c", r)
time.Sleep(delay)
}
}
}
func fib(x int) int {
if x < 2 {
return x
}
return fib(x-1) + fib(x-2)
}
func jsDatedotnow() int64 {
return time.Now().UnixNano() / 1e6
}
const then = Date.now()
const n = 45
const fibN = fib(n)
console.log("\rFibonacci(%s) = %s in %sms", n, fibN, Date.now() - then)
function fib (x){
if (x < 2)
return x
return fib(x-1) + fib(x-2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment