Go less memory than Java — Binary Tree Preorder Traversal

I just discovered that Golang implementations sometimes consume less memory than Java implementations, well at least in short programs.

The way Go and Java execute code is different, the first one is a compiled language to native code and the last one is a compiled language to bytecode. In other words Go compiler creates a native code, then once the program is run the computer loads the native code and executes it. On the other hand, Java starts the Java Virtual Machine (JVM), which is at the end a huge program, to interpret the bytecode. Finally, the JVM duplicates the code in the machine, using a technique called Just-in-time compilation (JIT compilation) to executes the dup code.

Even the simple “Binary Tree Preorder Traversal” consumes more memory in Java than Golang. In the following examples, the same algorithm consumes different memory, for what was briefly mentioned before.

Go:

func preorderTraversal(root *TreeNode) []int {
if root == nil {
return nil
}

var ans []int
traverse(root, &ans)
return ans
}
func traverse(root *TreeNode, ans *[]int) {
if root == nil {
return
}

*ans = append(*ans, root.Val)
traverse(root.Left, ans)
traverse(root.Right, ans)
}

Java:

class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
if (root == null) {
return new ArrayList<Integer>();
}

List<Integer> lst = new ArrayList<Integer>();
traverse(root, lst);
return lst;
}

public void traverse(TreeNode root, List<Integer> lst) {
if (root == null) return;

lst.add(root.val);
traverse(root.left, lst);
traverse(root.right, lst);
}
}

Both languages are used to tackle different problems, I don’t think it’s fair to compare them by how each one consumes memory. I know that many more differences, similarities, and peculiarities must be considered. However, the use of fewer resources is one of the keys to why Golang is so popular with cloud and microservices.

Btw, try other solutions in Leetcode to see how other languages consume memory.

https://leetcode.com/problems/binary-tree-preorder-traversal/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Daniel Carvallo

Daniel Carvallo

My primary goal of doing this is the intellectual curiosity, the seduction of adventure.