At XO, we initially used Node and Ruby to build interconnected services. We enjoy the obvious performance benefits of Node, as well as access to a large repository of existing packages. We can also easily distribute and reuse existing plug-ins and modules within the company. Greatly improve the efficiency of development, so that we can quickly write scalable and reliable applications. Also, the large Node community makes it easier for our engineers to contribute to open source software (such as BunnyBus and Felicity).

While I used more rigorously compiled languages like C++ and C# in college and some of my first jobs, I started using JavaScript. I love its freedom and flexibility, but I’ve recently started to miss static and structured languages because a colleague at the time got me interested in Go.

I went from writing JavaScript to writing Go, and I noticed a lot of similarities between the two languages. Both are quick to learn and easy to pick up, both have expressive syntax, and both have plenty of opportunities in the developer community. There is no perfect programming language, so you should always choose one that fits the project at hand. In this article, I’m going to explain the key differences between the two languages at a deeper level and hopefully encourage users who have never used Go to have the opportunity to use it.

General difference

Before diving into the details, we should first understand the important differences between the two languages.

Go, or Golang, is a free and open source programming language created by Google in 2007. It is designed for speed and simplicity. Go is compiled directly into machine code, which is where its speed comes from. Debugging in a compiled language is fairly easy because you can catch a lot of errors early on. Go is also strongly typed, helping with data integrity and finding type errors at compile time.

JavaScript, on the other hand, is a weakly typed language. In addition to the additional burden of ignoring the type of validation data and truth judgment traps, using a weakly typed language has its own benefits. Using currying and the flexible arity of a variable number of parameters makes functions more flexible than using interfaces and generics. JavaScript is interpreted at runtime, which can lead to error handling and debugging problems. Node is a JavaScript runtime based on the Google V8 virtual machine, which makes it a lightweight and fast Web development platform.

grammar

As a former JavaScript developer, Go’s simple and intuitive syntax appealed to me. Since the syntax of both languages can be said to have evolved from C, their syntax has a lot in common. Go is widely regarded as an “easy language to learn”. That’s because of its developer-friendly tools, concise syntax, and adherence to conventions.

Go contains a number of built-in features that help simplify development. You can compile your program into a binary executable using the Go build command using the standard Go build tools. Testing with the built-in test suite is simply a matter of running go Test. Features such as natively supported concurrency are even provided at the language level.

Google’s Go developers argue that programming today is too complex, with too much “bookkeeping, rework and paperwork.” This is why Go’s syntax is designed to be so simple and clean to reduce clutter, improve efficiency, and enhance readability. It also encourages developers to write unambiguous, easy-to-understand code. Go has only 25 reserved keywords and one loop (for loop), unlike JavaScript, which has about 84 keywords (including reserved keywords, objects, properties, and methods).

To illustrate some of the differences and similarities in syntax, let’s look at a few examples:

  • Punctuation: Go removes all superfluous symbols to improve efficiency and readability. Although symbols are rarely needed in JavaScript (see: Lisp) and are often optional, I prefer the simplicity of Go.
For (var I = 0; i < 10; i++) { console.log(i); } // Punctuation in JavaScriptCopy the code

// Go use the minimum number of punctuation marks for I := 0; i < 10; I ++ {fmt.println (I)} // Punctuation in GoCopy the code

  • Assignment: Since Go is strongly typed, you can use the := operator to do type inference when initializing variables to avoid duplicate declarations, whereas JavaScript declares types at run time.
Var foo = "bar"; // Assignment in JavaScriptCopy the code

Var foo string // Do not use type inference foo = "bar" foo := "bar" // Use type inference // Go assignmentCopy the code

  • Export: In JavaScript, you must explicitly export from a module. In Go, any uppercase function is exported by default.
const Bar = () => {}; Module.exports = {Bar} // exports in JavaScriptCopy the code

Func Bar (s string) string {// Bar will be exported} // Export in GoCopy the code

  • Import: In JavaScript the Required library is required to import dependencies and modules, while Go imports modules through the package path using the native import keyword. Another difference is that, unlike Node’s central NPM repository, Go uses urls as paths to import packages that are not standard libraries, in order to clone dependencies directly from the package source repository.
Var foo = require('foo'); foo.bar(); // JavaScript importCopy the code

// Go import import (" FMT "// Go's standard library part "github.com/foo/foo" // import directly from the repository) foo.bar () // Go importCopy the code

  • Return Value: Return values and errors can be gracefully passed and handled with Go’s multi-value return feature, and incorrect value passing is reduced by passing references. In JavaScript you need to return multiple values via an object or array.
Function foo() {return {a: 1, b: 2}; } const { a, b } = foo(); // JavaScript returnsCopy the code

Func foo() (int, int) {return 1, 2} a, b := foo() // Go returns multiple valuesCopy the code

  • Error handling: Go recommends catching errors where they occur, rather than bubbling them up in callbacks like Node does.
Foo ('bar', function(err, data) {// handle error} // handle error in JavaScriptCopy the code

Foo, err := bar() if err! = nil {// handle errors with defer, panic, recover, log.fatal, etc.} // Go error handlingCopy the code

  • Variable-argument functions: Both Go and JavaScript functions support passing in an indefinite number of arguments.
function foo (... args) { console.log(args.length); } foo(); // 0 foo(1, 2, 3); // 3 // variable argument functions in JavaScriptCopy the code

func foo (args ... Int) {fmt.println (len(args))} func main() {foo() // 0 foo(1,2,3) // 3} // the variable argument function in GoCopy the code

community

When it comes to comparing the programming paradigms offered by Go and Node, there are different advocates on both sides. Node completely beats Go in terms of the number of packages and the size of the community. Node Package Manager (NPM), the largest software repository in the world with over 410,000 packages, is growing at a staggering rate of 555 new packages per day. This number may seem surprising (and it is), but it is important to note that many of these packages are repetitive and not of sufficient quality to be used in a production environment. By comparison, Go has about 130,000 packages.

Number of Node and Go packages

Although Node and Go are about the same age, JavaScript is much more widely used and has a large developer and open source community. Because Node was developed for everyone and started with a robust package manager, Go was developed specifically for Google. The Spectrum leaderboard below shows the top Web development languages currently in vogue.

Top 7 Web development languages

The popularity of JavaScript seems to have held relatively steady in recent years, while Go has been on an upward trend.

Programming Language Trends

performance

What if your main focus is speed? Today there seems to be more emphasis on performance optimization than ever before. Users don’t like to wait for information. In fact, 40% of your users will stop visiting your site if it takes longer than three seconds to load.

Node is often considered a high-performance language because of its non-blocking asynchronous I/O. Also, as I mentioned earlier, Node runs on Google’S V8 engine, which is optimized for dynamic languages. Go is also designed with speed in mind. Google’s developers built an “expressive and lightweight type system; Concurrency and garbage collection mechanisms; Enforce dependency versions, etc. “to achieve this goal.

I ran some tests to compare the performance of Node and Go. These tests focus on the primary competencies provided by the language. If I’m going to test for things like HTTP requests or CPU-intensive operations, I use the Go language-level concurrency tool (Goroutines/Channels). But I focused more on the basic features each language provides (see Three concurrent methods for more on Goroutines and Channels).

I also included Python in the benchmark, so we were happy with the results for Node and Go anyway.

Loop/arithmetic

Iterate over a billion terms and add them up:

var r = 0;
for (var c = 0; c < 1000000000; c++) {
   r += c;
}

// Node
Copy the code

package main
func main() {
var r int
for c := 0; c < 1000000000; c++ {
       r += c
}
}

// Go
Copy the code

sum(xrange(1000000000))

// Python
Copy the code

The results of

The loser here is definitely Python, which took over 7 seconds of CPU time. Node and Go are fairly efficient, running at 900 ms and 408 ms, respectively.

Fixed: Due to some comments suggesting that Python performance could be improved. I updated the results to reflect these changes. At the same time, using PyPy greatly improves performance. When running with Python 3.6.1 and PyPy 3.5.7, performance improved to 1.234 seconds, but still not as good as Go and Node.

I/O

Iterate over a million numbers and write them to a file.

var fs = require('fs');
var wstream = fs.createWriteStream('node');

for (var c = 0; c < 1000000; ++c) {
  wstream.write(c.toString());
}
wstream.end();

// Node
Copy the code

package main

import (
  "bufio"
  "os"
  "strconv"
)

func main() {
  file, _ := os.Create("go")
  b := bufio.NewWriter(file)
  for c := 0; c < 1000000; c++ {
    num := strconv.Itoa(c)
    b.WriteString(num)
  }
  file.Close()
}

// Go
Copy the code

with open("python", "a") as text_file:
for i in range(1000000):
    text_file.write(str(i))

// Python
Copy the code

The results of

Python was third again with 7.82 seconds. In this test, the difference between Node and Go was significant, with Node taking about 1.172 seconds and Go 213 milliseconds. What’s really impressive about Go is that most of its processing time is spent compiling. If we compile the code and run it in binary, this I/O test takes just 78 milliseconds — 15 times faster than Node.

Fixed: Modified Go code to implement cache I/O.

Bubble sort

Sort an array of ten elements ten million times.

function bubbleSort(input) {
    var n = input.length;
    var swapped = true;
    while (swapped) {
        swapped = false;
        for (var i = 0; i < n; i++) {
            if (input[i - 1] > input [i]) {
                [input[i], input[i - 1]] = [input[i - 1], input[i]];
                swapped = true;
            }
        }
    }
}
for (var c = 0; c < 1000000; c++) {
    const toBeSorted = [1, 3, 2, 4, 8, 6, 7, 2, 3, 0];
    bubbleSort(toBeSorted);
}

// Node
Copy the code

package main
var toBeSorted [10]int = [10]int{1, 3, 2, 4, 8, 6, 7, 2, 3, 0}
func bubbleSort(input [10]int) {
    n := len(input)
    swapped := true
    for swapped {
        swapped = false
        for i := 1; i < n; i++ {
            if input[i-1] > input[i] {
                input[i], input[i-1] = input[i-1], input[i]
                swapped = true
            }
        }
    }
}
func main() {
    for c := 0; c < 1000000; c++ {
        bubbleSort(toBeSorted)
    }
}

// Go
Copy the code

def bubbleSort(input):
    length = len(input)
    swapped = True
    while swapped:
        swapped = False
        for i in range(1,length):
            if input[i - 1] > input[i]:
                input[i], input[i - 1] = input[i - 1], input[i]
                swapped = True
for i in range(1000000):
    toBeSorted = [1, 3, 2, 4, 8, 6, 7, 2, 3, 0]
    bubbleSort(toBeSorted)

//Python
Copy the code

The results of

As before, Python fared worst, taking about 15 seconds to complete the task. Go completes tasks 16 times faster than Node.

sentence

Go was the clear winner in all three tests, while Node performed well for the most part. Python is also doing well. To be clear, performance is not the only consideration when choosing a programming language. If your application doesn’t need to process a lot of data, the performance difference between Node and Go may be trivial. For some additional performance comparisons, see the following:

  • Node Vs. Go
  • Multiple Language Performance Test
  • Benchmarks Game

conclusion

This post is not meant to prove that one language is better than another. Each programming language has a place in the software development community for a variety of reasons. My intention is to highlight the differences between Go and Node and promote the emergence of a new Web development language. When choosing a language for a project, there are various factors to consider, such as developer familiarity, cost, and practicality. I encourage a thorough low-level analysis when deciding which language is right for you.

As we’ve seen, Go has the following advantages: performance close to the underlying language, a simple syntax, and a relatively simple learning curve make it ideal for building scalable and secure Web applications. With the rapid growth of Go usage and community activities, it will become an important player in modern web development. Having said that, I believe Node, if implemented correctly, is moving in the right direction and remains a powerful and useful language. It has a large following and an active community, making it a simple platform to get Web applications up and running at any time.

data

If you are interested in learning Go, check out the following resources:

  • Golang website
  • Golang Wiki
  • Golang Subreddit

via: https://medium.com/xo-tech/from-node-to-go-a-high-level-comparison-56c8b717324a#.byltlz535

By John Stamatakos translator: Trnhoe Proofread: WXY

This article is originally compiled by LCTT and released in Linux China