29.2 F
Columbus
Sunday, January 24, 2021

Are large slices more expensive than smaller ones?

This post was originally published on this site

Programmers have a tendency to be superstitious. Particularly, when a programmer hears that copies are expensive, they start to see them everywhere, especially when they learn that, in Go, every assignment is a copy.

Consider this code; x is three orders of magnitude larger than y, is the assignment of x to a more expensive than the assignment of y to b?

func f() {
       x, y := make([]byte, 9000), make([]byte, 9)
       a := x
       b := y
       // ...
 } 

The answer is; no. x and y have the same type, []byte, that is, a slice of bytes. As both variables have the same type, their assignment involves copying the same amount of data. Both assignments have the same cost.

All slices are the same size; three machine words (three uintptrs). The first word in the slice is a pointer to the slice’s backing array, the storage for the slice, the second word is the slice’s length, and the third is the capacity. Assigning one slice variable to another copies just three machine words.

Further reading: Go slices: usage and internals (blog.golang.org)

Related Articles

Live Stream: Using Maven in IntelliJ IDEA

Register now and join us for the live stream of ‘Using Maven in IntelliJ IDEA’. In this live stream, Java Champion and Java User Group...

Webinar Recording: What’s New in TeamCity 2020.2

The recording of our January 19 webinar, “What’s New in TeamCity 2020.2”, is now available. In this webinar, Marco Behler, the Developer Advocate in...

Webinar – OOPs, I did it again

Join us Thursday, February 11, 2021, 16:00 – 17:00 CET (10:00 AM – 11:00 AM EST or check other timezones) for our free live webinar, OOPs, I did...

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

21,412FansLike
0FollowersFollow
0SubscribersSubscribe
- Advertisement -

Latest Articles

Live Stream: Using Maven in IntelliJ IDEA

Register now and join us for the live stream of ‘Using Maven in IntelliJ IDEA’. In this live stream, Java Champion and Java User Group...

Webinar Recording: What’s New in TeamCity 2020.2

The recording of our January 19 webinar, “What’s New in TeamCity 2020.2”, is now available. In this webinar, Marco Behler, the Developer Advocate in...

Webinar – OOPs, I did it again

Join us Thursday, February 11, 2021, 16:00 – 17:00 CET (10:00 AM – 11:00 AM EST or check other timezones) for our free live webinar, OOPs, I did...

CUE: Configuration superpowers for everyone

On this episode we learn how to Configure, Unify, and Execute things. What’s CUE all about? Well, it’s an open source language with a...