Skip to content

Instantly share code, notes, and snippets.

@cyanly
Last active February 11, 2016 21:01
Show Gist options
  • Save cyanly/665fa6823b543aa084bb to your computer and use it in GitHub Desktop.
Save cyanly/665fa6823b543aa084bb to your computer and use it in GitHub Desktop.
Go-lang javascript methods benchmark

Javascript benchmark idea

function fib(n) {
  if (n < 2) return n;
  return fib(n - 2) + fib(n - 1);
}

console.log(fib(35));

Native GO

package main

import "fmt"

func fib(n int) int {
	if n < 2 {
		return n
	}

	return fib(n-2) + fib(n-1)
}

func main() {
	fmt.Println(fib(35))
}

Otto Javacript engine, pure go

package main

import (
	"github.com/robertkrimen/otto"
)

func DiscardSendSync(msg string) string { return "" }

func main() {

	vm := otto.New()
	vm.Run(`
function fib(n) {
  if (n < 2) return n;
  return fib(n - 2) + fib(n - 1);
}

console.log(fib(35));
	`)
}

Ducktape minimalism javascript engine in C with CGo binding

package main

import (
"github.com/olebedev/go-duktape"
"log"
)

func main() {
	ctx := duktape.New()
	if err := ctx.PevalString(`
function fib(n) {
  if (n < 2) return n;
  return fib(n - 2) + fib(n - 1);
}

print(fib(35));

	`); err != nil {
		log.Fatal(err)
	}
}

The Winner : V8 engine binding to Cgo then Go

package main

import (
	v8 "github.com/ry/v8worker"
	"log"
)

func DiscardSendSync(msg string) string { return "" }

func main() {

	worker1 := v8.New(func(msg string) {
		log.Println(msg)
	}, DiscardSendSync)

	err := worker1.Load("1.js", `
function fib(n) {
  if (n < 2) return n;
  return fib(n - 2) + fib(n - 1);
}

$print(fib(35));
`)
	if err != nil {
		log.Fatal(err)
	}
}

/usr/bin/time -f "CPU: %P MEM: %M"

~/temp/gov8$ time ./fib
9227465

real	0m0.059s
user	0m0.052s
sys	0m0.008s
CPU: 96% MEM: 2056

~/temp/gov8$ time node fib.js
9227465

real	0m0.157s
user	0m0.156s
sys	0m0.000s
CPU: 97% MEM: 22,752


~/temp/gov8$ time ./fibOtto 
9227465

real	2m45.801s
user	2m41.944s
sys	0m21.596s
CPU: 112% MEM: 11,180


~/temp/gov8$ time ./fibduk 
9227465

real	0m9.060s
user	0m9.048s
sys	0m0.004s
CPU: 99% MEM: 4,676


~/temp/gov8$ time ./fibv8 
9227465

real	0m0.108s
user	0m0.100s
sys	0m0.008s
CPU: 99% MEM: 12,676

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment