在golang中高效地旋转切片的方法

huangapple go评论105阅读模式
英文:

Efficient way to rotate a slice in golang

问题

我需要一个能够高效地反转golang切片的函数。(我具体的需求是反转[]byte的前缀)。

我查看了Effective Go中的示例,并使用objdump -Sd进行了检查,发现生成了大量用于检查数组索引的样板代码。甚至交换操作也不够高效。

英文:

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.

答案1

得分: 6

首先,我必须说一下:首先是个人资料。这真的是你代码中的瓶颈吗?如果是的话,你有几个选择。

1)禁用边界检查。我认为有一个未记录的编译器标志可以关闭切片边界检查。不过我现在找不到它了。(根据 OP 的说法,是 -B)。

2)用 C(或汇编)编写程序,你可以为 [586]c 编写 C 代码,并将其链接到你的 Go 包中(你需要包含一些来自 $GOROOT/src/pkg/runtime 的头文件),如下所示:

#include "runtime.h"
mypackage·swapslice(Slice s) {
    int i, j;
    //不是真正的交换循环
    for (i = 0, j = s.len - 1; i < j; i++, j--)
        //交换 s.arr[i] 和 s.arr[j];
}
英文:

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

huangapple
  • 本文由 发表于 2010年12月13日 20:45:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/4428937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定