How to fix VSCode's Go extension high CPU usage

Writing Go code could be much easier if you use an IDE or text-editor plugin. Fortunately, there are some very good plugins for my text-editors of choice:

  • vim-go plugin for VIM which provides Golang language support
  • and Go extension for VSCode which provides the same functionality in Visual Studio Code.

The VSCode Go plugin however has an issue (or maybe misconfiguration): When using Go modules, the extension causes high CPU load!

The problem

To be able to solve a problem we must first identify exactly what the problem is. When writing code in any language, VSCode is constantly running process(es) in background to be able to suggest autocompletion, intellisense, auto imports, and etc.

By default, the VSCode’s Go plugin uses gocode tool to be able to provide autocompletion which is, as far as I understood, very slow and CPU intensive. This is an screenshot of macOS activity monitor when writing Go code in VSCode:

GoCode high CPU load

The solution

To be able to provide autocompletion, the Go team provided gopls.

gopls (pronounced: “go please”) is the official language server for the Go language.

I’m not sure why the extension is not using the Go’s default gopls tool for autocompletion. Maybe because the Go extension for VSCode was originally developed by Microsoft; but, recently it is maintained by the Go team at Google. As written in Go extension page:

This is the new home for the VS Code Go extension. We just migrated from Microsoft/vscode-go. Learn more about our move on the Go blog.

Maybe they change it in future.

The good news is that you can change the configuration! All we need to do is to tell VSCode to use the gopls language server instead of gocode tool. To make coding in Go more enjoyable, I suggest to turn formatOnSave and organizeImports on as well.

"go.useLanguageServer": true,
"go.buildOnSave": "off",
"[go]": {
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "source.organizeImports": true,
    },
    "editor.snippetSuggestions": "none",
},
"[go.mod]": {
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "source.organizeImports": true,
    },
},
"gopls": {
    "usePlaceholders": true
}

Note: In some cases, gopls tool may not be installed. If so, you can install it manually:

go get -u golang.org/x/tools/gopls

I saw a significant performance increase After switching to gopls and it became more enjoyable to write Go code. I hope you experience the same.

I am starting to like Golang

Lock down during COVID-19 pandemic continues and we have no choice but to stay home. Although we have missed lots things, it gives us the opportunity to learn and read more.

During the last four years, nearly all projects I worked on was written in Python. I like Python and it’s getting better every day. However, in the last 3 months or so, I had enough time to get familiar with Golang!

Learning curve

As a developer with near 15 years of working experiences, learning a new programming language shouldn’t be too hard; but, Golang was different. In the decade, every app I have developed, from C++ to Python and everything in between, was written with an object-oriented programming language. The most difficult challenge I faced when started developing my first practical application in Go was the lack of OOP principals. However, the more I used Go, the more I realized things can be done differently!

Here are some examples:

Exported Names

For example, although Golang does not have the encapsulation features such as private, public, protected or friend, it has something called exported name! When a function or field starts capital letter, it will be considered as an exported name which means it can be accessed from other packages.

package tools

// Private function. It can be accessed only inside tools package.
func sum(a, b int) int {
    return a + b
}

// Exported function. Anyone can access this function from other packages.
func Multiply(a, b int) int {
    return a * b
}

Struct methods

As an another example, because Go is not an OOP language, it doesn’t have classes; however, just like C, it has structs. Structs are types that are collection of fields. But unlike C, structs can have related methods! Please take a look the following example:

package example

type Person struct {
    ID uint
    FirstName string
    LastName string
    Age uint
}

// C like functions to return the full name
func GetPersonFullName(p *Person) string {
    return p.FirstName + " " + p.LastName
}

// Go struct methods
func (p *Person) GetFullName() string {
    return p.FirstName + " " + p.LastName
}

It’s still possible to write C-like code and it’s totally fine; but it could be much cleaner it you use the second method. Now let’s use the two functions we have written above:

package example

p := &Person{
    ID: 1,
    FirstName: "Mohammad Mahdi",
    LastName: "Ramezanpour",
    Age: 33,
}

// Call the first function
fullName := GetPersonFullName(p)

// Call the struct method
fullName := p.GetFullName()

Pointers

Go is a modern programming language and it has almost everything any modern programming language has. But unlike most of them, it has pointers! As you may know, pointers are game changers when it comes to high-performance software development. But they can be problematic as well!

In low-level languages such as C or C++, the developer is responsible for managing the memory and as all humans make mistakes, one can take a part of memory from the OS and forget to free it which could lead to memory leaks and app crashes. This is why some high-level programming languages such as Java and C# has something called garbage collector (GC). GC is responsible for taking care of memory allocations that are not in use anymore.

The great news is that Go has both pointers and GC!!! This simply let you have control over the memory but if you make a mistake, Go will take care of it.

Last words

As I’m getting deeper into Golang world, I’m getting more and more excited about the language. If you haven’t tried Go, you should definitely check it out. It’s the language to learn.

Switching from Evernote

For the last 8 years or so, I have been using Evernote to take my notes and capture my ideas. I call myself a loyal customer to Evernote because I didn’t move to other alternatives even after they have restricted the number of concurrent devices to two! I waited for about 5 years to see some good new features and to be honest, the only good feature they have added since the first day I started using it was dark mode. I hope I could see some other features such as right-to-left languages support or better hierarchy category structure but they haven’t add any of these until now. So I decided to switch!

Options

I started investigating about other options I have to switch to. In fact, there are dozens of note-taking applications out there but in my opinion, only a few of them are deserved to be called an alternative to Evernote! Here is my shortlist:

  • Google Keep
  • Microsoft OneNote
  • Apple Notes

I tried Google Keep but the fact that it doesn’t have any desktop application really hurts me. It’s also more like sticky notes rather than “real notes”. Also, I have tried OneNote before. OneNote is really great option but I think it’s more intended to be used by students because it’s really similar to university textbooks. What I need in particular is a simple text area (similar to Evernote) where I can just type! Moreover, I want the support for RTL languages because I write my daily journal mostly in Persian.

Apple Notes

I know most people may blame me for choosing Apple Notes over all other alternatives; but, the fact is that it covers most of my needs! Here are some of my key point:

  • I own a MacBook and an iPhone; and as expected, Apple Notes works seamlessly on my devices.
  • It syncs automatically via iCloud and it can even be accessed via a web browser if I don’t carry any of my devices (which is rare but possible).
  • Apple Notes does support right-to-left languages (which Evernote doesn’t).
  • Just like Evernote, Apple Notes supports search in photos! If you scan a document for example, you can simply search through it.
  • It’s completely free! Unlike Evernote and most other alternatives, you can save notes up to your iCloud storage capacity (5GB by default)!

I believe you don’t use 80% of features apps offer (especially productivity apps) and I believe simplicity is good. Apple Notes is simply a note-taking application which offers only essentials and it’s enough.

Book Review - Educated

Educated I am not a fast reader (at least by now) and it took me little bit more time than others to read a passage. However, since I don’t have anything to do due to this pandemic, reading is the only thing I do.

Two days ago I was privileged to finish Educated and let me tell you this: it’s one of the best books I have ever read. It’s not a science-fiction but basically a memoir of its author, Tara Westover. I mentioned science-fiction because at first when I started the book I thought it is! It’s full of strange events happening around and I couldn’t believe that all of these wired events are happening in the 21st century.

Tara, has never been to school until the age of 17 because her parents believed public schools wash the kids minds so they keep their children at home as much as possible. To avoid schools they didn’t get birth certificates for some of their children. Tara has received hers at the age of 9!

In addition, Tara’s parents didn’t believe on hospitals as well! They thought human made (chemical) drugs will rot patients’ bodies from inside and they will kill them. So when her mother’s head injured badly during a car accident, her father took mother to home instead of hospital!

In some developing countries these kind of believes still exist. a small amount of

But Tara found her own way toward being Educated, she attended in a collage and started her new path of life until she awarded with PhD from Cambridge!

As a matter of fact, I want to talk about this book for days to reflect how fascinating it was, but at the same time, don’t want to spoil it.

I think this book is the one of those everyone should have at their bookshelves; so, go ahead and either purchase it online or from your local bookstore.

How to correct typos in VS code

This #StayAtHome trend has given me enough time (more than enough actually) to try out new things; from changing my development fonts after 6 years, or to try out new themes.

I have recently moved from “all other editors and IDEs” to Visual Studio Code and trying to make it my new home. One of the things I believe every text editor should have is spell checking. Unfortunately, VSCode does not have spell checking out of the box but there is an extension for it thanks to the community.

Code Spell Checker

The extension is Code Spell Checker. What it does is providing a basic spell checking that also supports camelCase. Although it’s very simple and works right out of the box, it’s highly configurable as well. For example, you may want to disable spell checking for a specific programming language. In this case you can add the following configuration to your settings.json:

"cSpell.enableFiletypes": [
    "!go" // ! excludes go extension
]

In addition, following are other configurations you may want to manipulate:

// The Language local to use when spell checking. "en", "en-US" and "en-GB" are currently supported by default.
"cSpell.language": "en",

// Controls the maximum number of spelling errors per document.
"cSpell.maxNumberOfProblems": 100,

// Controls the number of suggestions shown.
"cSpell.numSuggestions": 8,

// The minimum length of a word before checking it against a dictionary.
"cSpell.minWordLength": 4,

// Specify file types to spell check.
"cSpell.enabledLanguageIds": [
    "csharp",
    "go",
    "javascript",
    "javascriptreact",
    "markdown",
    "php",
    "plaintext",
    "typescript",
    "typescriptreact",
    "yml"
],

// Enable / Disable the spell checker.
"cSpell.enabled": true,

// Display the spell checker status on the status bar.
"cSpell.showStatus": true,

// Words to add to dictionary for a workspace.
"cSpell.words": [],

// Enable / Disable compound words like 'errormessage'
"cSpell.allowCompoundWords": false,

// Words to be ignored and not suggested.
"cSpell.ignoreWords": ["behaviour"],

// User words to add to dictionary.  Should only be in the user settings.
"cSpell.userWords": [],

// Specify paths/files to ignore.
"cSpell.ignorePaths": [
    "node_modules",        // this will ignore anything the node_modules directory
    "**/node_modules",     // the same for this one
    "**/node_modules/**",  // the same for this one
    "node_modules/**",     // Doesn't currently work due to how the current working directory is determined.
    "vscode-extension",    //
    ".git",                // Ignore the .git directory
    "*.dll",               // Ignore all .dll files.
    "**/*.dll"             // Ignore all .dll files
],

// flagWords - list of words to be always considered incorrect
// This is useful for offensive words and common spelling errors.
// For example "hte" should be "the"`
"cSpell.flagWords": ["hte"],

// Set the delay before spell checking the document. Default is 50.
"cSpell.spellCheckDelayMs": 50,

You can also contribute to this project: https://github.com/streetsidesoftware/vscode-spell-checker