我使用 GWT JSNI 访问 native JavaScript 库。
我想知道我通过 JSNI 传递哪种数据类型的速度是否有任何差异。
示例 1:
public static native int test(int value) /*-{
return this.computeSomething(value);
}-*/;
示例 2:
public static native double test(double value) /*-{
return this.computeSomething(value);
}-*/;
假设computeSomething()接受整数值作为参数并返回一个整数值。
我是否必须按照此处建议的方式转换返回值:How to work with int values in gwt jsni methods
对 JSNI 函数使用 int 或 double 会对性能产生影响吗?
有没有办法从 JSNI 返回一个 int 类型?这里似乎有一个错误:https://code.google.com/p/google-web-toolkit/issues/detail?id=2693
最佳答案
当您从 Java 调用 JS 时,编译器相信 JSNI 代码完全遵循方法签名。这意味着如果 double
值从 int
返回方法,您可能会在其他地方得到其他效果。这会产生以下结果:
- 如果您不信任 JS 代码返回正确的类型,则需要进行强制转换。例如,如果方法声明了一个 int,但 js 代码可能返回一个 double,则应该强制转换为 int。您链接的问题更多的是关于返回 null 而不是数字。
就性能而言,根本没有区别。由于 GWT 假设 JS 将执行您所说的操作,因此它不会执行任何额外的工作来验证这一点(除了在开发模式下,作为验证代码是否有意义的一种方式)
有多种方法可以将 JS 数字(可能是 float )转换为整数,以便您可以确定 GWT/Java 代码可以接受它。第一个是简单地返回
double
,然后在您的 Java 代码中,转换为int
,或使用Math.round
删除任何不需要的精度。另外就是在你的JSNI中做什么com.google.gwt.dom.client.Element#toInt32
从 GWT 2.6 开始:/** * Fast helper method to convert small doubles to 32-bit int. * * <p>Note: you should be aware that this uses JavaScript rounding and thus * does NOT provide the same semantics as <code>int b = (int) someDouble;</code>. * In particular, if x is outside the range [-2^31,2^31), then toInt32(x) would return a value * equivalent to x modulo 2^32, whereas (int) x would evaluate to either MIN_INT or MAX_INT. */ private static native int toInt32(double val) /*-{ return val | 0; }-*/;
注意
| 0
的使用与|| 0
在您链接的答案中 - 第一个是按位“或”,第二个是 boolean “或”。返回
int
没有问题来自 JSNI - 链接的问题是关于返回java.lang.Integer
,围绕int
的盒装 Java 类型。这个问题是有缺陷的,因为不需要JsArray<Integer>
自com.google.gwt.core.client.JsArrayNumber
已经存在,您只需转换为 int 即可处理舍入问题。
关于java - 使用 int 或 double 作为 JSNI 函数时,性能有什么不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23155397/