Is []*T faster than []T?

Is a slice of values faster than a slice of pointers?

Should I pass data by value or by reference for optimal speed?

Questions like these are almost always a sign of premature optimization.

Moreover, even when it's time to optimize code for speed, these questions probably lead nowhere.

Why?

Because such questions call for micro-benchmarking isolated operations. However, there are many moving parts to consider that can heavily distort the measurements.

  • CPUs use a hierarchy of ultra-fast RAM for caching data from the main memory. Certain operations are not exactly cache-friendly.
  • Modern CPUs are very complex and do a great deal of hardware-level optimization. It thus can happen that even small changes to the code, like reordering functions in the source code, can change the results of microbenchmarks considerably.
  • A microbenchmark does not cover the garbage collector's work to clean up heap-allocated slice elements. Is this extra work significant or negligible?

So when asking whether []*T is faster than []T, the answer almost always depends on the larger context in which that slice is used because then, you can collect more details about the problem:

  • How large or small can this slice become?
  • How large or small can the elements become?
  • What are the most frequent operations on this slice? Insert, append, sort,…?
  • Is this slice passed to functions often? Is it used as a return parameter?
  • Should the slice data be copied along when it's passed around? (Remember that without any additional measurements, only the slice header is passed by value. Then the original slice and the copy point to the same underlying array.)

Last not least, the choice of using pointers should primarily be driven by the desired behavior. Passing a copy of a value around means the original data cannot be modified by the receivers of the copy. Passing a pointer around allows every receiver of the pointer to modify the original data. So using a pointer is first and foremost a decision about code logic, not speed.