在golang中旋转切片的有效方法

在golang中旋转切片的有效方法

问题描述:

I need a function to efficiently reverse 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.

我需要一个函数来有效反转golang中的切片。 (我的具体需要是反转[] byte的前缀)。 p>

我从 objdump -Sd code>的#for“ rel =” nofollow“>有效Go ,并生成大量样板来检查数组索引。 甚至交换也没有效率。 p> div>

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];
}