WASM(不使用Blazor)对于大型数字数组非常慢。

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

WASM (without Blazor) is very slow for large number arrays

问题

我正在尝试通过将C#代码发布为WebAssembly来在JavaScript中使用我的C#代码。大多数情况下都可以正常工作,但对于大型数字数组则存在问题。

在我的C#代码中,我有一个简单的方法如下:

        [JSInvokable]
        public static double[] Test(double[] a, double[] b)
        {
            return new double[];
        }

然后我发布了JavaScript代码,在JavaScript中调用了这个方法:

var temp = dotnet.MyTest.test(a, b);

其中a和b是数字数组,每个数组都有100万个元素。

获取temp的返回值大约需要40秒时间。直接调用相同的测试方法的C#调用会立即返回。

我是否遗漏了什么?

英文:

I'm trying to use my c# code in my JavaScript by publishing the c# code as webassembly. It works for the most part, except for large number arrays.

In my c# code, I have a simple method like this:

        [JSInvokable]
        public static double[] Test(double[] a, double[] b)
        {
            return new double[];
        }

then I publish the js and in my JavaScript, I call the method:

var temp = dotnet.MyTest.test(a, b);

where a and b are number arrays. Each has 1 million elements.

It took about 40 seconds for temp to get the return value. A direct c# call to the same test method would return immediately.

Am I missing anything?

答案1

得分: 2

When passing a double[] from Javascript to WASM.

We need to do something called marshalling of the data.

In this case, the default behavior for marshalling of a JS array into a double[] is to copy the array.

That is pretty slow.

The only way I know that might be possible for you to achieve fast interop with huge arrays of Number, would be for you to:

  • Pre allocate a large array from dotnet.
  • Pin the array
  • Pass the memory address from dotnet to JS
  • Wrap the wrap the address + size in a DataView (using the WASM memory object)
  • Write to the DataView
  • Call the DotNet method using offsets and size pointers, and construct Span
  • Profit
英文:

When passing a double[] from Javascript to WASM.

We need to do something called marshalling of the data.

In this case, the default behavior for marshalling of a JS array into a double[] is to copy the array.

That is pretty slow.

The only way I know that might be possible for you to achieve fast interop with huge arrays of Number, would be for you to:

  • Pre allocate a large array from dotnet.
  • Pin the array
  • Pass the memory address from dotnet to JS
  • Wrap the wrap the address + size in a DataView (using the WASM memory object)
  • Write to the DataView
  • Call the DotNet method using offsets and size pointers, and construct Span<double>
  • Profit

huangapple
  • 本文由 发表于 2023年7月13日 13:05:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76676088.html
匿名

发表评论

匿名网友

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

确定