开发者

Efficient way to rotate a slice in golang

开发者 https://www.devze.com 2023-01-30 12:37 出处:网络
I need a function to efficiently rever开发者_开发问答se a slice in golang. (My concrete need is to reverse the prefix of a []byte).

I need a function to efficiently rever开发者_开发问答se a slice in golang. (My concrete need is to reverse the prefix of a []byte).

I checked the example from Effective Go with objdump -Sd and a lot of boiler plate is generated to check for array indexes. Even the swap is too inefficient.


Firstly, I have to say it: Profile first. Is this really a bottleneck in your code? If it is, you have a few options.

1) Disable bounds checking. I think there's an undocumented compiler flag that turns of slice bounds checking. I can't find it at the moment though. (EDIT: -B according to OP).

2) Write the routine in C (or assembler), you can write C for [586]c and link in your go package (you'll need to include some headers from $GOROOT/src/pkg/runtime), like so:

#include "runtime.h"
mypackage·swapslice(Slice s) {
    int i, j;
    //Not a real swap loop
    for (i = 0, j = s.len - 1; i < j; i++, j--)
        //swap s.arr[i] and s.arr[j];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号