-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
improvement: Use go1.21's slices package to avoid allocation in sorting
- Loading branch information
Showing
3 changed files
with
55 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
// Copyright (c) 2023 Palantir Technologies. All rights reserved. | ||
// Use of this source code is governed by a BSD-style | ||
// license that can be found in the LICENSE file. | ||
|
||
//go:build !go1.21 | ||
|
||
package metrics | ||
|
||
import ( | ||
"sort" | ||
) | ||
|
||
// sortStrings is the default sort.Strings function. | ||
// Unfortunately this forces the slice to escape to the heap. | ||
// See https://github.com/golang/go/issues/17332 | ||
// Go 1.21's slices package does not have this issue. | ||
var sortStrings = sort.Strings | ||
|
||
// sortTags is the default sort.Sort function. | ||
// Unfortunately this forces the slice to escape to the heap. | ||
// See https://github.com/golang/go/issues/17332 | ||
// Go 1.21's slices package does not have this issue. | ||
var sortTags = sort.Sort |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
// Copyright (c) 2023 Palantir Technologies. All rights reserved. | ||
// Use of this source code is governed by a BSD-style | ||
// license that can be found in the LICENSE file. | ||
|
||
//go:build go1.21 | ||
|
||
package metrics | ||
|
||
import ( | ||
"slices" | ||
) | ||
|
||
// sortStrings is the default slices.Sort function which does not force allocation like sort.Strings. | ||
var sortStrings = slices.Sort[[]string] | ||
|
||
// sortTags uses slices.SortFunc which does not force allocation like sort.Sort. | ||
func sortTags(tags Tags) { | ||
slices.SortFunc(tags, compareTags) | ||
} | ||
|
||
func compareTags(a, b Tag) int { | ||
switch { | ||
case a.keyValue > b.keyValue: | ||
return 1 | ||
case a.keyValue == b.keyValue: | ||
return 0 | ||
default: | ||
return -1 | ||
} | ||
} |