Optimizing Go code without a Blindfold

Optimizing Go code without a Blindfold

Optimizing Go code without a Blindfold: Making code faster is exciting, and benchmarks in Go make that easy to do! Optimizing a program can be complex and require careful consideration to do properly. Daniel demonstrates techniques and tools which are a must for any performance aficionado.

Making code faster is exciting, and benchmarks in Go make that easy to do! Not really. Optimizing a program can be complex and require careful consideration to do properly. Daniel demonstrates techniques and tools which are a must for any performance aficionado.

Go Programming and Why should you learn Go Language?

Go Programming and Why should you learn Go Language?

Go provides you high performance like C/C++, super efficient concurrency handling like Java and fun to code like Python/Perl. Go with Golang and why go is the best programming language in the world and Why should you learn Go Language?

Why Learn Go Lang - Should I go with 'Go' | Brief Intro to Go Language

Go with Golang and why go is the best programming language in the world.

We will talk about:

  1. Power of GoLang
  2. Is Go for everyone
  3. Who said Go is better than Nodejs
  4. Who are the creators of GoLang
  5. Why GoLang was created by Google
  6. Why Learn of GoLang
  7. Companies using GoLang
  8. What GoLang have and what not
  9. GoLang Garbage Collection
  10. GoLang Concurrency
  11. Recommended Books for Learning GoLang

Rust vs. Go: Should I Rust, or Should I Go

Rust vs. Go: Should I Rust, or Should I Go

Well both Rust and Go provide amazing performance. Should you write you’re next big thing with Rust or with Go? Go is fast and powerful, but it avoids bogging the developer down, focusing instead on simplicity and uniformity. Rust. If on the other hand, wringing out every last ounce of performance is a necessity, then Rust should be your choice. Rust is more of a competitor to C++ than it is with Go.

Should I stay, or should I go?” Great song by the band The Clash. I’m listening to it, right now, while I’m writing this article. The song debuted back in 1982, a long time ago. Back then, I was just a kid exploring a new hobby — programming my Atari 2600. The first video game I ever wrote was written using 6502 Assembly for that console. The compiler for it cost about $65, if I recall, which at the time equated to mowing ~13 or so lawns.

The game was simple: using the joystick, maneuver your spaceship through a randomly generated scrolling cave. The cave walls were sinusoidal, scrolling vertically on the left and right sides of the screen, and you had to make sure your craft didn’t crash into them. I know, I know: Not that sophisticated. But I was only ten or eleven years old at the time.

Despite the “power” of the processor, computing sine values at run-time was simply too much for it. So, using my handy Texas Instruments calculator, I pre-calculated a bunch of the sine values, carefully writing them down on paper, and then entering them in as constants for the game. This greatly enhanced the performance of the game, and made it usable.

So what’s my point? What’s any of this got to do with Rust or Go?

Today’s languages are far more advanced than 6502 Assembly, which make it easier to write complex programs. It took a lot of my time to write that game, and I could do it much faster today, with less code than I did back then. But which language today provides that magic combination of simplicity and power?

Well both Rust and Go provide amazing performance. They both compile to machine code, the Holy Grail of performance. And with today’s processing power, developers can do amazing things with either of these languages. So the question is: Should you write you’re next big thing with Rust or with Go?

With a quick search, you can easily find several articles that go into detail about the differences between the two languages. But the focus of this article is the bang for the buck, that magic combination of performance per line of code.

To put it another way, where is that sweet spot of simple code and top-end performance? And in this case, is it Rust, or is it Go?
There really isn’t any argument: Rust is faster than Go. In the benchmarks above, Rust was faster, and in some cases, an order of magnitude faster.

But before you run off choosing to write everything in Rust, consider that Go wasn’t that far behind it in many of those benchmarks, and it’s still much faster than the likes of Java, C#, JavaScript, Python and so on. So in other words, it’s almost a wash between Rust and Go on the axis of performance. Now, if what you’re building needs to wring out every last ounce of performance, then by all means, choose Rust. But if what you need is top-of-the-line performance, then you’ll be ahead of the game choosing either of these two languages.

So then we’re down to the complexity of the code. This is where things can be muddy since this can be more subjective than performance benchmarks. Let’s look at a simple exercise: building a small web server that prints out “Hello World” when it receives an HTTP request. To do this in Rust, it looks something like this:

use std::net::{TcpStream, TcpListener};
use std::io::{Read, Write};
use std::thread;


fn handle_read(mut stream: &TcpStream) {
    let mut buf = [0u8; 4096];
    match stream.read(&mut buf) {
        Ok(_) => {
            let req_str = String::from_utf8_lossy(&buf);
            println!("{}", req_str);
            },
        Err(e) => println!("Unable to read stream: {}", e),
    }
}

fn handle_write(mut stream: TcpStream) {
    let response = b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n<html><body>Hello world</body></html>\r\n";
    match stream.write(response) {
        Ok(n) => println!("Response sent: {} bytes", n),
        Err(e) => println!("Failed sending response: {}", e),
    }
}

fn handle_client(stream: TcpStream) {
    handle_read(&stream);
    handle_write(stream);
}

fn main() {
    let port = "8080";
    let listener = TcpListener::bind(format!("127.0.0.1:{}", port)).unwrap();
    println!("Listening for connections on port {}", port);

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                thread::spawn(|| {
                    handle_client(stream)
                });
            }
            Err(e) => {
                println!("Unable to connect: {}", e);
            }
        }
    }
}

Something pretty similar in Go looks like this:

package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
)

type handler struct{}

func (theHandler *handler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	log.Printf("Received request: %s\n", request.URL)
	log.Printf("%v\n", request)
	io.WriteString(writer, "Hello world!")
}

const port = "8080"

func main() {
	server := http.Server{
		Addr:    fmt.Sprintf(":%s", port),
		Handler: &handler{},
	}

	server.ListenAndServe()
}

Now, they are not 100% exactly the same, but they are close enough. The difference between them is ~20 lines of code. Rust definitely forces the developer to consider more, and thus write more code than Go.

Another example: Consider one of the more difficult aspects of software development: multi-threading. When tackling something like this, as you undoubtedly would when building an HTTP server, there’s a lot to think about:

  • You need to ensure everything you design is thread safe (locks)
  • You need to handle communication between threads (channels)
  • You have to design with concurrency and parallelism in mind (threads and routines)

Both Rust and Go handle these hurdles really efficiently, but Go requires less effort. With Rust, you have way more options, and thus more power, when spawning threads. Just look at some of the documentation on this. Here’s just one way to spawn a thread in Rust:

use std::thread;

let handler = thread::spawn(|| {
    // thread code
});

handler.join().unwrap();

On the other hand, here’s how to create something similar using Go:

go someFunction(args)

Another crucial part of writing code is handling errors. Here I think Rust and Go are quite similar. Rust enables the developer to handle errors cases through the use of the enum return types: Option<T>and Result<T, E>. The Option<T> will return either None or Some(T) whereas Result<T, E> will return either Ok(T) or Err(T). Given that most of Rust’s own libraries, as well as other third-party libraries, return one of these types, the developer will usually have to handle the case where nothing is returned, or where an error is returned.

Here’s a simple example of the Result type being returned by a function in Rust:

fn foo_divide(a: f32, b: f32) -> Result<f32, &'static str> {
    if b == 0.0 {
        Err("divide by zero error!")
    } else {
        Ok(a / b)
    }
}fn main() {
    match foo_divide(5.0, 4.0) {
        Err(err) => println!("{}", err),
        Ok(result) => println!("5 / 4 = {}", result),
    }
}

Notice that the Err case must be handled within the match statement.

Go, on the other hand, leaves this more up to the developer, since errors can be ignored using the _. However, idiomatic Go strongly recommends returning an error, especially since functions in Go can return multiple values. Therefore, it’s easy to have functions return their intended value along with an error, if there is one.

Here is the corresponding example from above done in Go:

func fooDivide(a float32, b float32) (float32, error) {
    if b == 0 {
        return 0, errors.New("divide by zero error!")
    }    return a / b, nil
}func main() {
    result, err := fooDivide(5, 4)
    if err != nil {
       log.Printf("an error occurred: %v", err)
    } else {
       log.Printf("The answer is: 5 / 4 = %f", result)
    }
}

Notice that this line:

result, err := fooDivide(5, 4)

could have been written as

result, _ := fooDivide(5, 4)

In the latter case, the error returned would have been ignored.

Honestly, they’re both pretty similar, except for Rust forcing error checking. Otherwise, there’s little difference, and it’s difficult to find an advantage one has over the other. To my eyes, this is a draw.

I could keep going, digging deeper into other language differences. But the bottom line, from threads, to channels, to generics, Rust provides the developer with more options. In this respect, Rust is closer to C++ than Go. Does this make Rust inherently more complex?

I think so, yes.

So here are my recommendations:

  • Either. If you’re building a web service that handles high load, that you want to be able to scale both vertically and horizontally, either language will suit you perfectly.
  • Go. But if you want to write it faster, perhaps because you have many different services to write, or you have a large team of developers, then Go is your language of choice. Go gives you concurrency as a first-class citizen, and does not tolerate unsafe memory access (neither does Rust), but without forcing you to manage every last detail. Go is fast and powerful, but it avoids bogging the developer down, focusing instead on simplicity and uniformity.
  • Rust. If on the other hand, wringing out every last ounce of performance is a necessity, then Rust should be your choice. Rust is more of a competitor to C++ than it is with Go. Having battled with C++, Rust feels just as powerful but with many happy improvements. Rust empowers developers to have control over every last detail of how their threads behave with the rest of the system, how errors should be handled, and even the lifetime of their variables!
  • Rust. Rust was designed to interoperate with C. Go can as well, but gives up a lot to achieve this goal, and it’s not really its focus.
  • Go. If readability is a requirement, go with Go. It’s far too easy to make your code hard for others to grok with Rust.

I hope you enjoyed reading this!

Go vs. Rust: What's the difference, Which is Better and Why?

Go vs. Rust: What's the difference, Which is Better and Why?

Go vs. Rust: What's the difference, Which is Better and Why? Look into the difference between Go and Rust. The differences that go beyond Rust use cases and Golang use cases. Let us answer Which is better: Rust or Go?

If you had to make a list of top programming languages that appeared in the industry in the past decade, the two names that would emerge would be Go and Rust.

And, if you had to sit down and think of the programming languages which were best aligned with the motive to develop secure, microservice favoring frameworks and apps, you would again find yourself staring at the two languages.

Even after being similar in some prominent ways like maturity, being open source, and being designed for microservice oriented, modern, parallel computing environments, there is a lot of confusion around Go vs. Rust and which of the two languages are good for the developer community to enter into.

The intent of this article today is to look into the difference between Go and Rust in much detail. The differences that go beyond Rust use cases and Golang use cases.

Let us answer Which is better: Rust or Go?

But before that, let us refresh the basics of both the programming languages.

Rust Programming Language

Rust language came into existence back in 2010. Deemed as one of the ML languages’ extensions, the aim that the language was expected to fulfill was better security, performance, improved parallelism, and greater modularity.

The feature set that Rust comes with has brought it to a stage where there are very few developers who haven’t heard of it or as showing an unwillingness to work in it.

Advantage of Rust language:

  • Amazing run speed
  • Enables fine grain features such as rich patterns, syntax extensions, and novel embeddings.
  • Interoperable with C, and FFI, amongst others.
  • Zero-cost abstraction
  • Predictable runtime behaviour
  • Saves crashing, debugging time.

Disadvantage of Rust language:

  • Learning Rust is steeper than Go
  • Between Go vs Rust, it is slow to compile
  • It is slower than the C and C++ language in the analogous conditions.

Go Programming Language

Go coding language was introduced back in 2007 by Google. It was looked at as a language that had emerged to solve the issues that organizations face when developing software infrastructure. The Go language specification was devised to introduce garbage collection, dependency management, built-in concurrency, robustness across multiple boundaries between the components, etc.

The result of the well thought of features of Go has gotten it a market position which is enough to bring it several points ahead in the Go vs Rust debate.

Advantage of Go Language:

  • The best feature of Go language is the incredible speed at which it compiles to machine code.
  • The simplicity of code
  • Concise, pragmatic, and efficient
  • Flexible and highly concurrency favoring
  • Strong interoperability with C language.

Disadvantage of Go Language:

  • Keeps simplicity over performance
  • Lacks the generics to an extent
  • Not enough immutability
  • Not a system language.

Now that we have looked into the basics of both the languages, let us get on to the part where we look into how they stack up against each other.

Rust vs Go: Performance

The one factor that weighs up Rust in the Rust vs Go debate is performance. The programs have been designed to run at similar or near similar speed of C++ and C.

Go, on the other hand, trade runtime speed for convenience, by making tasks automatic. But in terms of Rust vs Go Performance comparison, development speed of Go falls several steps behind the high performance that Rust offers.

Go vs Rust: Memory Management

Rust make use of compile time ownership strategy for memory management through zero cost abstractions. If a Rust program is not memory safe, it won’t be able to cross the compilation stage.

Like Rust, Go is also memory safe. But in the case of Go, it is handled automatically during the runtime. Meaning, developers won’t have to think of releasing or allocating memory when writing code.

Go vs Rust: Development Speed

At times, the development speed becomes more important than the program speed. A working example of this can be seen in the case of Python, which is not one of the fastest languages to run but fastest to write a software in.

Go comes with the same appeal. The simplicity and directness that it offers makes it faster than a number of languages in the market.

Rust, on the other hand, comes with more language features and thus takes longer to master. Its compile speed is also longer than Go’s. So, if the intent is of faster development cycle, you would be better off with Go than Rust.

Rust vs Go: Concurrency

Modern day apps are distributed and networked. The languages that haven’t planned for these realities are far off behind the curve. The developers have to be able to run the tasks independently and share state between the tasks minus the risk of data corruption.

Now while concurrency was built into Golang’s syntax from beginning, Rust recently gained the native syntax in the form of async/.await. But even though the concurrency of Rust lacks the developer experience that went behind Go, it makes up for it through Rust’s memory safety.

Conclusion

We could keep digging into both the languages, dissecting both sides of Go vs Rust comparison, but the ultimate answer to the Rust and Go comparison would be the fact that it depends. There are instances where Rust is better than Go and vice versa.

Ultimately, this is what we recommend as an app development company, who works on both –

Choose Rust when:
  • If performance is a necessity
  • If you want it to interoperate with C language.
  • When your developers need control on every detail of how the threads behave with the rest of the system, how the errors must be handled, it would be better to look into Rust use cases.

Choose Go when:

  • If readability is a must have requirement
  • If you wish to write codes faster
  • If the focus is on uniformity and simplicity.
FAQs About Go vs Rust

Q. Why Go and not Rust?

The answer to this would be in when and not why. You should go with Golang when – you have to write code faster, when simplicity is a bit more important than performance, and when readability is a must have necessity.

Q. What does Go and Rust have in common?

There are some prevalent similarities between Go web development and Rust, mostly in terms of the maturity and the fact that both: the programming features of Rust and Go are open source and have been designed for microservice oriented, modern, parallel computing environments.

Q. Is Go faster than Rust?

Yes. Speed is one of the biggest differences between Go and Rust – a difference which is won by Go.