1

I have a slice that contains pointers to values. In a performance-critical part of my program, I'm adding or removing values from this slice. For the moment, inserting a value is just an append (O(1) complexity), and removal consists in searching the slice for the corresponding pointer value, from 0 to n-1, until the pointer is found (O(n)). To improve performance, I'd like to sort values in the slice, so that searching can be done using dichotomy (so O(log(n)).

But how can I compare pointer values? Pointer arithmetic is forbidden in go, so AFAIK to compare pointer values p1 and p2 I have to use the unsafe package and do something like

uintptr(unsafe.Pointer(p1)) < uintptr(unsafe.Pointer(p2))

Now, I'm not comfortable using unsafe, at least because of its name. So, is that method correct? Is it portable? Are there potential pitfalls? Is there a better way to define an order on pointer values? I know I could use maps, but maps are slow as hell.

icza
  • 389,944
  • 63
  • 907
  • 827
Fabien
  • 12,486
  • 9
  • 44
  • 62
  • 4
    There are no guarantees from the language specification about what pointer values are and even if they'll ever stay the same during the execution of a program (so that compacting garbage collection isn't made impossible). Because of that it is a very bad idea to use pointers as anything other than something that points to a value. Does it have to be a slice? Since ordering on pointers is meaningless anyway the only thing you achieve is uniqueness, can't you use maps instead? – Art Feb 14 '18 at 13:41
  • Thanks @Art. I tried using maps, but they are way slower than slices in this context. – Fabien Feb 14 '18 at 13:54

1 Answers1

3

As said by others, don't do this. Performance can't be that critical to resort to pointer arithmetic in Go.

Pointers are comparable, Spec: Comparison operators:

Pointer values are comparable. Two pointer values are equal if they point to the same variable or if both have value nil. Pointers to distinct zero-size variables may or may not be equal.

Just use a map with the pointers as keys. Simple as that. Yes, indexing maps is slower than indexing slices, but then again, if you'd want to keep your slice sorted and you wanted to perform binary searches in that, then the performance gap decreases, as the (hash) map implementation provides you O(1) lookup while binary search is only O(log n). In case of big data set, the map might even be faster than searching in the slice.

If you anticipate a big number of pointers in the map, then pre-allocate a big one with make() passing an estimated upper size, and until your map exceeds this size, no reallocation will occur.

m := make(map[*mytype]struct{}, 1<<20) // Allocate map for 1 million entries
icza
  • 389,944
  • 63
  • 907
  • 827
  • Thank you, I'll have to try that, I didn't know `make` could accept a second parameter for maps. – Fabien Feb 14 '18 at 14:47