From 00c214e53513e01afdbfdddca6503e0fef6dfdb3 Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Mon, 9 Nov 2026 11:24:20 +0500 Subject: [PATCH 01/16] perf(android): pass Java to JS call arguments as primitive arrays --- .../jsi/callbackhandlers/CallbackHandlers.cpp | 4 +- .../jsi/callbackhandlers/CallbackHandlers.h | 2 +- .../ffi/jni/jsi/conversion/ArgConverter.cpp | 75 ++++++++++------- .../ffi/jni/jsi/conversion/ArgConverter.h | 5 +- .../ffi/jni/jsi/conversion/JavaCallArgs.h | 15 ++++ .../callbackhandlers/CallbackHandlers.cpp | 4 +- .../napi/callbackhandlers/CallbackHandlers.h | 2 +- .../ffi/jni/napi/conversion/ArgConverter.cpp | 75 +++++++++++------ .../ffi/jni/napi/conversion/ArgConverter.h | 5 +- .../ffi/jni/napi/conversion/JavaCallArgs.h | 15 ++++ NativeScript/runtime/android/jsi/Runtime.cpp | 4 +- NativeScript/runtime/android/jsi/Runtime.h | 3 +- .../runtime/android/jsi/com_tns_Runtime.cpp | 4 +- NativeScript/runtime/android/napi/Runtime.cpp | 4 +- NativeScript/runtime/android/napi/Runtime.h | 3 +- .../runtime/android/napi/com_tns_Runtime.cpp | 4 +- .../src/main/java/com/tns/Runtime.java | 81 ++++++++++++------- 17 files changed, 203 insertions(+), 102 deletions(-) create mode 100644 NativeScript/ffi/jni/jsi/conversion/JavaCallArgs.h create mode 100644 NativeScript/ffi/jni/napi/conversion/JavaCallArgs.h diff --git a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp index c703e25b..4ed7e808 100644 --- a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp @@ -1134,7 +1134,7 @@ vector CallbackHandlers::GetTypeMetadata(const string &name, int index) JsValue CallbackHandlers::CallJSMethod(JsRuntime &rt, JNIEnv *_jEnv, const JsValue &jsObject, jclass claz, const string &methodName, int javaObjectId, - jobjectArray args) { + const JavaCallArgs &args) { JEnv jEnv(_jEnv); auto runtime = Runtime::GetRuntime(rt); @@ -1161,7 +1161,7 @@ JsValue CallbackHandlers::CallJSMethod(JsRuntime &rt, JNIEnv *_jEnv, // a throw. engine:: propagates a JS throw as a JSError, so the equivalent is // to let it unwind and convert it here. try { - int argc = jEnv.GetArrayLength(args) / 3; + int argc = ArgConverter::GetJavaArgsLength(jEnv, args); if (argc > 0) { JsValue *jsArgs = nullptr; JsValue stack_args[8]; diff --git a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h index 628dd1d2..b2f99eba 100644 --- a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h +++ b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h @@ -68,7 +68,7 @@ namespace tns { static JsValue CallJSMethod(JsRuntime &rt, JNIEnv *jEnv, const JsValue &jsObject, jclass claz, - const std::string &methodName, int javaObjectId, jobjectArray args); + const std::string &methodName, int javaObjectId, const JavaCallArgs &args); static JsValue GetJavaField(JsRuntime &rt, const JsValue &caller, diff --git a/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp b/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp index e7929e6f..54ccfa02 100644 --- a/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp +++ b/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp @@ -1,4 +1,6 @@ #include "ArgConverter.h" +#include +#include #include "ObjectManager.h" #include "Util.h" #include "NativeScriptException.h" @@ -137,55 +139,75 @@ JsValue ArgConverter::NativeScriptLongFunctionCallback(JsRuntime &rt, const JsVa } } -void ArgConverter::ConvertJavaArgsToJsArgs(JsRuntime &rt, jobjectArray args, size_t argc, +int ArgConverter::GetJavaArgsLength(JNIEnv *env, const JavaCallArgs &args) { + return args.types == nullptr ? 0 : env->GetArrayLength(args.types); +} + +void ArgConverter::ConvertJavaArgsToJsArgs(JsRuntime &rt, const JavaCallArgs &args, size_t argc, JsValue *arr) { JEnv jenv; - auto runtime = Runtime::GetRuntime(rt); - auto objectManager = runtime->GetObjectManager(); + constexpr size_t kInlineArgs = 16; + jint inlineTypes[kInlineArgs]; + jlong inlineValues[kInlineArgs]; + std::vector heapTypes; + std::vector heapValues; + jint *types = inlineTypes; + jlong *values = inlineValues; + if (argc > kInlineArgs) { + heapTypes.resize(argc); + heapValues.resize(argc); + types = heapTypes.data(); + values = heapValues.data(); + } - int jArrayIndex = 0; - for (int i = 0; i < argc; i++) { - JniLocalRef argTypeIDObj(jenv.GetObjectArrayElement(args, jArrayIndex++)); - JniLocalRef arg(jenv.GetObjectArrayElement(args, jArrayIndex++)); - JniLocalRef argJavaClassPath(jenv.GetObjectArrayElement(args, jArrayIndex++)); + JNIEnv *jni = jenv; + jni->GetIntArrayRegion(args.types, 0, argc, types); + jni->GetLongArrayRegion(args.values, 0, argc, values); - Type argTypeID = (Type) JType::IntValue(jenv, argTypeIDObj); + auto runtime = Runtime::GetRuntime(rt); + auto objectManager = runtime->GetObjectManager(); + for (size_t i = 0; i < argc; i++) { + jlong bits = values[i]; JsValue jsArg; - switch (argTypeID) { + switch (static_cast(types[i])) { case Type::Boolean: - jsArg = JsValue(JType::BooleanValue(jenv, arg) == JNI_TRUE); + jsArg = JsValue(bits != 0); break; case Type::Char: - jsArg = jcharToJsString(rt, JType::CharValue(jenv, arg)); + jsArg = jcharToJsString(rt, static_cast(bits)); break; case Type::Byte: - jsArg = JsValue((double) JType::ByteValue(jenv, arg)); - break; case Type::Short: - jsArg = JsValue((double) JType::ShortValue(jenv, arg)); - break; case Type::Int: - jsArg = JsValue((double) JType::IntValue(jenv, arg)); - break; case Type::Long: - jsArg = JsValue((double) JType::LongValue(jenv, arg)); + jsArg = JsValue(static_cast(bits)); break; - case Type::Float: - jsArg = JsValue((double) JType::FloatValue(jenv, arg)); + case Type::Float: { + auto raw = static_cast(bits); + float value; + memcpy(&value, &raw, sizeof(value)); + jsArg = JsValue(static_cast(value)); break; - case Type::Double: - jsArg = JsValue((double) JType::DoubleValue(jenv, arg)); + } + case Type::Double: { + double value; + memcpy(&value, &bits, sizeof(value)); + jsArg = JsValue(value); break; - case Type::String: - jsArg = jstringToJsString(rt, (jstring) arg); + } + case Type::String: { + JniLocalRef str(jni->GetObjectArrayElement(args.refs, i)); + jsArg = jstringToJsString(rt, (jstring) str); break; + } case Type::JsObject: { - jint javaObjectID = JType::IntValue(jenv, arg); + auto javaObjectID = static_cast(bits); jsArg = objectManager->GetJsObjectByJavaObject(javaObjectID); if (js_util::is_null_or_undefined(jsArg)) { + JniLocalRef argJavaClassPath(jni->GetObjectArrayElement(args.refs, i)); string argClassName = jstringToString(ObjectToString(argJavaClassPath)); argClassName = Util::ConvertFromCanonicalToJniName(argClassName); jsArg = objectManager->CreateJSWrapper(javaObjectID, argClassName); @@ -199,7 +221,6 @@ void ArgConverter::ConvertJavaArgsToJsArgs(JsRuntime &rt, jobjectArray args, siz arr[i] = jsArg; } - } JsValue ArgConverter::ConvertFromJavaLong(JsRuntime &rt, jlong value) { diff --git a/NativeScript/ffi/jni/jsi/conversion/ArgConverter.h b/NativeScript/ffi/jni/jsi/conversion/ArgConverter.h index aec02fe4..9efc6b06 100644 --- a/NativeScript/ffi/jni/jsi/conversion/ArgConverter.h +++ b/NativeScript/ffi/jni/jsi/conversion/ArgConverter.h @@ -11,6 +11,7 @@ #include "Runtime.h" #include "NativeScriptAssert.h" #include "JEnv.h" +#include "JavaCallArgs.h" #include #include @@ -20,7 +21,9 @@ namespace tns { public: static void Init(JsRuntime &rt); - static void ConvertJavaArgsToJsArgs(JsRuntime &rt, jobjectArray args, size_t length, + static int GetJavaArgsLength(JNIEnv *env, const JavaCallArgs &args); + + static void ConvertJavaArgsToJsArgs(JsRuntime &rt, const JavaCallArgs &args, size_t length, JsValue *arr); static JsValue ConvertFromJavaLong(JsRuntime &rt, jlong value); diff --git a/NativeScript/ffi/jni/jsi/conversion/JavaCallArgs.h b/NativeScript/ffi/jni/jsi/conversion/JavaCallArgs.h new file mode 100644 index 00000000..adb165c2 --- /dev/null +++ b/NativeScript/ffi/jni/jsi/conversion/JavaCallArgs.h @@ -0,0 +1,15 @@ +#ifndef JAVACALLARGS_H_ +#define JAVACALLARGS_H_ + +#include "jni.h" + +namespace tns { + // The arrays com.tns.Runtime.packageArgs builds for a Java -> JS call. + struct JavaCallArgs { + jintArray types; + jlongArray values; + jobjectArray refs; + }; +} + +#endif /* JAVACALLARGS_H_ */ diff --git a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp index 5efd897f..c39afb84 100644 --- a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp @@ -1174,7 +1174,7 @@ vector CallbackHandlers::GetTypeMetadata(const string &name, int index) napi_value CallbackHandlers::CallJSMethod(napi_env env, JNIEnv *_jEnv, napi_value jsObject, jclass claz,const string &methodName,int javaObjectId, - jobjectArray args) { + const JavaCallArgs &args) { JEnv jEnv(_jEnv); napi_status status; napi_value result; @@ -1203,7 +1203,7 @@ napi_value CallbackHandlers::CallJSMethod(napi_env env, JNIEnv *_jEnv, bool exceptionPending; NAPI_GUARD(napi_is_exception_pending(env, &exceptionPending)) {} - int argc = jEnv.GetArrayLength(args) / 3; + int argc = ArgConverter::GetJavaArgsLength(jEnv, args); if (argc > 0) { napi_value* jsArgs = nullptr; napi_value stack_args[8]; diff --git a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h index 274bba27..68934b43 100644 --- a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h +++ b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h @@ -64,7 +64,7 @@ namespace tns { static napi_value CallJSMethod(napi_env env, JNIEnv *jEnv, napi_value jsObject,jclass claz, - const std::string &methodName,int javaObjectId, jobjectArray args); + const std::string &methodName,int javaObjectId, const JavaCallArgs &args); static napi_value GetJavaField(napi_env env, napi_value caller, FieldCallbackData *fieldData, ObjectManager *objectManager = nullptr, diff --git a/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp b/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp index 7f3cccf6..a1e7aeb8 100644 --- a/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp +++ b/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp @@ -1,4 +1,6 @@ #include "ArgConverter.h" +#include +#include #include "ObjectManager.h" #include "Util.h" #include "NativeScriptException.h" @@ -183,55 +185,77 @@ napi_value ArgConverter::NativeScriptLongFunctionCallback(napi_env env, napi_cal return nullptr; } -void ArgConverter::ConvertJavaArgsToJsArgs(napi_env env, jobjectArray args, size_t argc, napi_value* arr) { +int ArgConverter::GetJavaArgsLength(JNIEnv *env, const JavaCallArgs &args) { + return args.types == nullptr ? 0 : env->GetArrayLength(args.types); +} + +void ArgConverter::ConvertJavaArgsToJsArgs(napi_env env, const JavaCallArgs &args, size_t argc, napi_value* arr) { napi_status status; JEnv jenv; - auto runtime = Runtime::GetRuntime(env); - auto objectManager = runtime->GetObjectManager(); + constexpr size_t kInlineArgs = 16; + jint inlineTypes[kInlineArgs]; + jlong inlineValues[kInlineArgs]; + std::vector heapTypes; + std::vector heapValues; + jint *types = inlineTypes; + jlong *values = inlineValues; + if (argc > kInlineArgs) { + heapTypes.resize(argc); + heapValues.resize(argc); + types = heapTypes.data(); + values = heapValues.data(); + } - int jArrayIndex = 0; - for (int i = 0; i < argc; i++) { - JniLocalRef argTypeIDObj(jenv.GetObjectArrayElement(args, jArrayIndex++)); - JniLocalRef arg(jenv.GetObjectArrayElement(args, jArrayIndex++)); - JniLocalRef argJavaClassPath(jenv.GetObjectArrayElement(args, jArrayIndex++)); + JNIEnv *jni = jenv; + jni->GetIntArrayRegion(args.types, 0, argc, types); + jni->GetLongArrayRegion(args.values, 0, argc, values); - Type argTypeID = (Type) JType::IntValue(jenv, argTypeIDObj); + auto runtime = Runtime::GetRuntime(env); + auto objectManager = runtime->GetObjectManager(); + for (size_t i = 0; i < argc; i++) { + jlong bits = values[i]; napi_value jsArg; - switch (argTypeID) { + switch (static_cast(types[i])) { case Type::Boolean: - NAPI_GUARD(napi_get_boolean(env, JType::BooleanValue(jenv, arg), &jsArg)) {} + NAPI_GUARD(napi_get_boolean(env, bits != 0, &jsArg)) {} break; case Type::Char: - jsArg = jcharToJsString(env, JType::CharValue(jenv, arg)); + jsArg = jcharToJsString(env, static_cast(bits)); break; case Type::Byte: - NAPI_GUARD(napi_create_int32(env, JType::ByteValue(jenv, arg), &jsArg)) {} - break; case Type::Short: - NAPI_GUARD(napi_create_int32(env, JType::ShortValue(jenv, arg), &jsArg)) {} - break; case Type::Int: - NAPI_GUARD(napi_create_int32(env, JType::IntValue(jenv, arg), &jsArg)) {} + NAPI_GUARD(napi_create_int32(env, static_cast(bits), &jsArg)) {} break; case Type::Long: - NAPI_GUARD(napi_create_int64(env, JType::LongValue(jenv, arg), &jsArg)) {} + NAPI_GUARD(napi_create_int64(env, bits, &jsArg)) {} break; - case Type::Float: - NAPI_GUARD(napi_create_double(env, JType::FloatValue(jenv, arg), &jsArg)) {} + case Type::Float: { + auto raw = static_cast(bits); + float value; + memcpy(&value, &raw, sizeof(value)); + NAPI_GUARD(napi_create_double(env, value, &jsArg)) {} break; - case Type::Double: - NAPI_GUARD(napi_create_double(env, JType::DoubleValue(jenv, arg), &jsArg)) {} + } + case Type::Double: { + double value; + memcpy(&value, &bits, sizeof(value)); + NAPI_GUARD(napi_create_double(env, value, &jsArg)) {} break; - case Type::String: - jsArg = jstringToJsString(env, (jstring) arg); + } + case Type::String: { + JniLocalRef str(jni->GetObjectArrayElement(args.refs, i)); + jsArg = jstringToJsString(env, (jstring) str); break; + } case Type::JsObject: { - jint javaObjectID = JType::IntValue(jenv, arg); + auto javaObjectID = static_cast(bits); jsArg = objectManager->GetJsObjectByJavaObject(javaObjectID); if (napi_util::is_null_or_undefined(env, jsArg)) { + JniLocalRef argJavaClassPath(jni->GetObjectArrayElement(args.refs, i)); string argClassName = jstringToString(ObjectToString(argJavaClassPath)); argClassName = Util::ConvertFromCanonicalToJniName(argClassName); jsArg = objectManager->CreateJSWrapper(javaObjectID, argClassName); @@ -245,7 +269,6 @@ void ArgConverter::ConvertJavaArgsToJsArgs(napi_env env, jobjectArray args, size arr[i] = jsArg; } - } napi_value ArgConverter::ConvertFromJavaLong(napi_env env, jlong value) { diff --git a/NativeScript/ffi/jni/napi/conversion/ArgConverter.h b/NativeScript/ffi/jni/napi/conversion/ArgConverter.h index c7e270a0..7bf6f947 100644 --- a/NativeScript/ffi/jni/napi/conversion/ArgConverter.h +++ b/NativeScript/ffi/jni/napi/conversion/ArgConverter.h @@ -11,6 +11,7 @@ #include "Runtime.h" #include "NativeScriptAssert.h" #include "JEnv.h" +#include "JavaCallArgs.h" #include #include @@ -20,7 +21,9 @@ namespace tns { public: static void Init(napi_env env); - static void ConvertJavaArgsToJsArgs(napi_env env, jobjectArray args, size_t length, napi_value* arr); + static int GetJavaArgsLength(JNIEnv *env, const JavaCallArgs &args); + + static void ConvertJavaArgsToJsArgs(napi_env env, const JavaCallArgs &args, size_t length, napi_value* arr); static napi_value ConvertFromJavaLong(napi_env env, jlong value); diff --git a/NativeScript/ffi/jni/napi/conversion/JavaCallArgs.h b/NativeScript/ffi/jni/napi/conversion/JavaCallArgs.h new file mode 100644 index 00000000..adb165c2 --- /dev/null +++ b/NativeScript/ffi/jni/napi/conversion/JavaCallArgs.h @@ -0,0 +1,15 @@ +#ifndef JAVACALLARGS_H_ +#define JAVACALLARGS_H_ + +#include "jni.h" + +namespace tns { + // The arrays com.tns.Runtime.packageArgs builds for a Java -> JS call. + struct JavaCallArgs { + jintArray types; + jlongArray values; + jobjectArray refs; + }; +} + +#endif /* JAVACALLARGS_H_ */ diff --git a/NativeScript/runtime/android/jsi/Runtime.cpp b/NativeScript/runtime/android/jsi/Runtime.cpp index 9453db71..19d35863 100644 --- a/NativeScript/runtime/android/jsi/Runtime.cpp +++ b/NativeScript/runtime/android/jsi/Runtime.cpp @@ -713,7 +713,7 @@ int Runtime::GetReader() { jobject Runtime::CallJSMethodNative(JNIEnv *_jEnv, jobject obj, jint javaObjectID, jclass claz, jstring methodName, - jint retType, jboolean isConstructor, jobjectArray packagedArgs) { + jint retType, jboolean isConstructor, const JavaCallArgs &args) { JEnv jEnv(_jEnv); engine::Runtime &rt = engineHost->GetRuntime(); @@ -739,7 +739,7 @@ Runtime::CallJSMethodNative(JNIEnv *_jEnv, jobject obj, jint javaObjectID, jclas DEBUG_WRITE("CallJSMethodNative called jsObject %s", method_name.c_str()); auto jsResult = CallbackHandlers::CallJSMethod(rt, jEnv, jsObject, claz, method_name, - javaObjectID, packagedArgs); + javaObjectID, args); if (jsResult.isUndefined() || jsResult.isNull()) return nullptr; diff --git a/NativeScript/runtime/android/jsi/Runtime.h b/NativeScript/runtime/android/jsi/Runtime.h index 86c96691..51084b11 100644 --- a/NativeScript/runtime/android/jsi/Runtime.h +++ b/NativeScript/runtime/android/jsi/Runtime.h @@ -2,6 +2,7 @@ #define RUNTIME_H #include "jni.h" +#include "JavaCallArgs.h" #include #include #include "JniLocalRef.h" @@ -166,7 +167,7 @@ namespace tns { jobject CallJSMethodNative(JNIEnv *_env, jobject obj, jint javaObjectID, jclass claz, jstring methodName, jint retType, jboolean isConstructor, - jobjectArray packagedArgs); + const JavaCallArgs &args); void PassExceptionToJsNative(JNIEnv *env, jobject obj, jthrowable exception, jstring message, diff --git a/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp b/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp index 74313fa8..63cd3f55 100644 --- a/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp +++ b/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp @@ -200,7 +200,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_runScript(JNIEnv* _env, jobjec #endif -extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName,jint retType, jboolean isConstructor, jobjectArray packagedArgs) { +extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName,jint retType, jboolean isConstructor, jintArray argTypes, jlongArray argValues, jobjectArray argRefs) { JEnv::EntryScope envScope(_env); jobject result = nullptr; auto runtime = TryGetRuntime(runtimeId); @@ -208,7 +208,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en JSScope scope(runtime->GetEngineHost()); try { - result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, retType, isConstructor, packagedArgs); + result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, retType, isConstructor, JavaCallArgs{argTypes, argValues, argRefs}); } catch (NativeScriptException& e) { e.ReThrowToJava(&runtime->GetJSRuntime()); } catch (std::exception e) { diff --git a/NativeScript/runtime/android/napi/Runtime.cpp b/NativeScript/runtime/android/napi/Runtime.cpp index fdfe29cd..771a95e0 100644 --- a/NativeScript/runtime/android/napi/Runtime.cpp +++ b/NativeScript/runtime/android/napi/Runtime.cpp @@ -661,7 +661,7 @@ int Runtime::GetReader() { jobject Runtime::CallJSMethodNative(JNIEnv *_jEnv, jobject obj, jint javaObjectID, jclass claz, jstring methodName, - jint retType, jboolean isConstructor, jobjectArray packagedArgs) { + jint retType, jboolean isConstructor, const JavaCallArgs &args) { JEnv jEnv(_jEnv); DEBUG_WRITE("CallJSMethodNative called javaObjectID=%d", javaObjectID); @@ -679,7 +679,7 @@ Runtime::CallJSMethodNative(JNIEnv *_jEnv, jobject obj, jint javaObjectID, jclas DEBUG_WRITE("CallJSMethodNative called jsObject %s", method_name.c_str()); - auto jsResult = CallbackHandlers::CallJSMethod(env, jEnv, jsObject, claz,method_name, javaObjectID,packagedArgs); + auto jsResult = CallbackHandlers::CallJSMethod(env, jEnv, jsObject, claz,method_name, javaObjectID, args); if (napi_util::is_null_or_undefined(env, jsResult)) return nullptr; diff --git a/NativeScript/runtime/android/napi/Runtime.h b/NativeScript/runtime/android/napi/Runtime.h index 8d4abf9a..77b25f96 100644 --- a/NativeScript/runtime/android/napi/Runtime.h +++ b/NativeScript/runtime/android/napi/Runtime.h @@ -2,6 +2,7 @@ #define RUNTIME_H #include "jni.h" +#include "JavaCallArgs.h" #include #include #include "JniLocalRef.h" @@ -138,7 +139,7 @@ namespace tns { jobject CallJSMethodNative(JNIEnv *_env, jobject obj, jint javaObjectID, jclass claz, jstring methodName, jint retType, jboolean isConstructor, - jobjectArray packagedArgs); + const JavaCallArgs &args); void PassExceptionToJsNative(JNIEnv *env, jobject obj, jthrowable exception, jstring message, diff --git a/NativeScript/runtime/android/napi/com_tns_Runtime.cpp b/NativeScript/runtime/android/napi/com_tns_Runtime.cpp index cbb4b594..1ad9db98 100644 --- a/NativeScript/runtime/android/napi/com_tns_Runtime.cpp +++ b/NativeScript/runtime/android/napi/com_tns_Runtime.cpp @@ -180,7 +180,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_runScript(JNIEnv* _env, jobjec return result; } -extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName,jint retType, jboolean isConstructor, jobjectArray packagedArgs) { +extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName,jint retType, jboolean isConstructor, jintArray argTypes, jlongArray argValues, jobjectArray argRefs) { JEnv::EntryScope envScope(_env); jobject result = nullptr; auto runtime = TryGetRuntime(runtimeId); @@ -188,7 +188,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en NapiScope scope(runtime->GetNapiEnv()); try { - result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, retType, isConstructor, packagedArgs); + result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, retType, isConstructor, JavaCallArgs{argTypes, argValues, argRefs}); } catch (NativeScriptException& e) { e.ReThrowToJava( runtime->GetNapiEnv()); } catch (std::exception e) { diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java index f08f4d87..f1eb1409 100644 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -60,7 +60,7 @@ private native void attachNativeScript(int runtimeId, String metadataPath, long private native Object runScript(int runtimeId, String filePath) throws NativeScriptException; - private native Object callJSMethodNative(int runtimeId, int javaObjectID, Class claz, String methodName, int retType, boolean isConstructor, Object... packagedArgs) throws NativeScriptException; + private native Object callJSMethodNative(int runtimeId, int javaObjectID, Class claz, String methodName, int retType, boolean isConstructor, int[] argTypes, long[] argValues, Object[] argRefs) throws NativeScriptException; private native void createJSInstanceNative(int runtimeId, Object javaObject, int javaObjectID, String canonicalName); @@ -1263,36 +1263,55 @@ private Object callJSMethodImpl(Integer javaObjectID, Object javaObject, String return result; } - // Packages args in format (typeID, value, null) except for objects where it is - // (typeid, javaObjectID, canonicalName) - // if javaObject has no javaObjecID meaning javascript object does not - // exists for this object we assign one. - private Object[] packageArgs(Object... args) { - int len = (args != null) ? (args.length * 3) : 0; - Object[] packagedArgs = new Object[len]; - - if (len > 0) { - int jsArgsIndex = 0; - - for (int i = 0; i < args.length; i++) { - Object value = args[i]; - int typeId = TypeIDs.GetObjectTypeId(value); - String javaClassPath = null; - - if (typeId == TypeIDs.JsObject) { - javaClassPath = value.getClass().getName(); - value = getOrCreateJavaObjectID(value); + private static final class PackagedArgs { + int[] types; + long[] values; + Object[] refs; + } + + // Packages args as parallel arrays: the type id and the raw bits of each primitive, plus a + // reference only for strings (the string) and objects (the canonical class name). A javaObject + // with no javaObjectID, meaning javascript has no object for it yet, is assigned one. + private PackagedArgs packageArgs(Object... args) { + PackagedArgs packaged = new PackagedArgs(); + if (args == null || args.length == 0) { + return packaged; + } + + int len = args.length; + packaged.types = new int[len]; + packaged.values = new long[len]; + + for (int i = 0; i < len; i++) { + Object value = args[i]; + int typeId = TypeIDs.GetObjectTypeId(value); + packaged.types[i] = typeId; + + if (typeId == TypeIDs.Boolean) { + packaged.values[i] = ((Boolean) value) ? 1L : 0L; + } else if (typeId == TypeIDs.Char) { + packaged.values[i] = (Character) value; + } else if (typeId == TypeIDs.Byte || typeId == TypeIDs.Short || typeId == TypeIDs.Int || typeId == TypeIDs.Long) { + packaged.values[i] = ((Number) value).longValue(); + } else if (typeId == TypeIDs.Float) { + packaged.values[i] = Float.floatToRawIntBits((Float) value); + } else if (typeId == TypeIDs.Double) { + packaged.values[i] = Double.doubleToRawLongBits((Double) value); + } else if (typeId == TypeIDs.string) { + if (packaged.refs == null) { + packaged.refs = new Object[len]; } - - packagedArgs[jsArgsIndex++] = typeId; - - packagedArgs[jsArgsIndex++] = value; - - packagedArgs[jsArgsIndex++] = javaClassPath; + packaged.refs[i] = value; + } else if (typeId == TypeIDs.JsObject) { + if (packaged.refs == null) { + packaged.refs = new Object[len]; + } + packaged.refs[i] = value.getClass().getName(); + packaged.values[i] = getOrCreateJavaObjectID(value); } } - return packagedArgs; + return packaged; } static Class getClassForName(String className) { @@ -1370,9 +1389,9 @@ private Object dispatchCallJSMethodNative(final int javaObjectID, Class claz, boolean enableMultithreadedJavascript = this.cachedEnableMultithreadedJavascript; if (enableMultithreadedJavascript || isWorkThread) { - Object[] packagedArgs = packageArgs(tmpArgs); + PackagedArgs packagedArgs = packageArgs(tmpArgs); try { - ret = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, returnType, isConstructor, packagedArgs); + ret = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, returnType, isConstructor, packagedArgs.types, packagedArgs.values, packagedArgs.refs); } catch (NativeScriptException e) { if (discardUncaughtJsExceptions) { String errorMessage = "Error on \"" + Thread.currentThread().getName() + "\" thread for callJSMethodNative\n"; @@ -1392,8 +1411,8 @@ private Object dispatchCallJSMethodNative(final int javaObjectID, Class claz, public void run() { synchronized (this) { try { - final Object[] packagedArgs = packageArgs(tmpArgs); - arr[0] = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, returnType, isCtor, packagedArgs); + final PackagedArgs packagedArgs = packageArgs(tmpArgs); + arr[0] = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, returnType, isCtor, packagedArgs.types, packagedArgs.values, packagedArgs.refs); } catch (NativeScriptException e) { if (discardUncaughtJsExceptions) { String errorMessage = "Error on \"" + Thread.currentThread().getName() + "\" thread for callJSMethodNative\n"; From 7d420a38578ebb71ff1031acaa280f2e531e9eb1 Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 09:40:18 +0500 Subject: [PATCH 02/16] perf(android): keep the cached JNIEnv and its pinned flag in one thread_local --- NativeScript/ffi/jni/jsi/jni/JEnv.cpp | 11 +++++------ NativeScript/ffi/jni/jsi/jni/JEnv.h | 26 +++++++++++++++++++------- NativeScript/ffi/jni/napi/jni/JEnv.cpp | 11 +++++------ NativeScript/ffi/jni/napi/jni/JEnv.h | 26 +++++++++++++++++++------- 4 files changed, 48 insertions(+), 26 deletions(-) diff --git a/NativeScript/ffi/jni/jsi/jni/JEnv.cpp b/NativeScript/ffi/jni/jsi/jni/JEnv.cpp index 1c27d1cb..2b5f29eb 100644 --- a/NativeScript/ffi/jni/jsi/jni/JEnv.cpp +++ b/NativeScript/ffi/jni/jsi/jni/JEnv.cpp @@ -21,13 +21,13 @@ JNIEnv *JEnv::GetEnvSlow() { } void JEnv::PinThreadEnv(JNIEnv *env) { - s_threadEnv = env; - s_threadEnvPinned = true; + s_thread.env = env; + s_thread.pinned = true; } void JEnv::UnpinThreadEnv() { - s_threadEnv = nullptr; - s_threadEnvPinned = false; + s_thread.env = nullptr; + s_thread.pinned = false; } JEnv::operator JNIEnv* () const { @@ -855,8 +855,7 @@ void JEnv::CheckForJavaException() { } JavaVM *JEnv::s_jvm = nullptr; -thread_local JNIEnv *JEnv::s_threadEnv = nullptr; -thread_local bool JEnv::s_threadEnvPinned = false; +thread_local JEnv::ThreadEnv JEnv::s_thread; robin_hood::unordered_map JEnv::s_classCache; robin_hood::unordered_map JEnv::s_missingClasses; jclass JEnv::RUNTIME_CLASS = nullptr; diff --git a/NativeScript/ffi/jni/jsi/jni/JEnv.h b/NativeScript/ffi/jni/jsi/jni/JEnv.h index 597cc637..b7eafa88 100644 --- a/NativeScript/ffi/jni/jsi/jni/JEnv.h +++ b/NativeScript/ffi/jni/jsi/jni/JEnv.h @@ -8,7 +8,7 @@ namespace tns { class JEnv { public: - JEnv() : m_env(s_threadEnv != nullptr ? s_threadEnv : GetEnvSlow()) {} + JEnv() : m_env(CachedOrSlowEnv()) {} JEnv(JNIEnv *jniEnv) : m_env(jniEnv != nullptr ? jniEnv : JEnv().m_env) {} @@ -451,17 +451,24 @@ namespace tns { static void UnpinThreadEnv(); + private: + struct ThreadEnv { + JNIEnv *env = nullptr; + bool pinned = false; + }; + + public: class EntryScope { public: - explicit EntryScope(JNIEnv *env) : m_active(!s_threadEnvPinned), m_previous(s_threadEnv) { + explicit EntryScope(JNIEnv *env) : m_thread(s_thread), m_active(!m_thread.pinned), m_previous(m_thread.env) { if (m_active) { - s_threadEnv = env; + m_thread.env = env; } } ~EntryScope() { - if (m_active && !s_threadEnvPinned) { - s_threadEnv = m_previous; + if (m_active && !m_thread.pinned) { + m_thread.env = m_previous; } } @@ -470,6 +477,7 @@ namespace tns { EntryScope &operator=(const EntryScope &) = delete; private: + ThreadEnv &m_thread; bool m_active; JNIEnv *m_previous; }; @@ -477,12 +485,16 @@ namespace tns { private: static JNIEnv *GetEnvSlow(); + static JNIEnv *CachedOrSlowEnv() { + JNIEnv *env = s_thread.env; + return env != nullptr ? env : GetEnvSlow(); + } + void CheckForJavaException(); JNIEnv *m_env; - static thread_local JNIEnv *s_threadEnv; - static thread_local bool s_threadEnvPinned; + static thread_local ThreadEnv s_thread; static JavaVM *s_jvm; diff --git a/NativeScript/ffi/jni/napi/jni/JEnv.cpp b/NativeScript/ffi/jni/napi/jni/JEnv.cpp index 9ec0c093..d18c92e6 100644 --- a/NativeScript/ffi/jni/napi/jni/JEnv.cpp +++ b/NativeScript/ffi/jni/napi/jni/JEnv.cpp @@ -21,13 +21,13 @@ JNIEnv *JEnv::GetEnvSlow() { } void JEnv::PinThreadEnv(JNIEnv *env) { - s_threadEnv = env; - s_threadEnvPinned = true; + s_thread.env = env; + s_thread.pinned = true; } void JEnv::UnpinThreadEnv() { - s_threadEnv = nullptr; - s_threadEnvPinned = false; + s_thread.env = nullptr; + s_thread.pinned = false; } JEnv::operator JNIEnv* () const { @@ -855,8 +855,7 @@ void JEnv::CheckForJavaException() { } JavaVM *JEnv::s_jvm = nullptr; -thread_local JNIEnv *JEnv::s_threadEnv = nullptr; -thread_local bool JEnv::s_threadEnvPinned = false; +thread_local JEnv::ThreadEnv JEnv::s_thread; robin_hood::unordered_map JEnv::s_classCache; robin_hood::unordered_map JEnv::s_missingClasses; jclass JEnv::RUNTIME_CLASS = nullptr; diff --git a/NativeScript/ffi/jni/napi/jni/JEnv.h b/NativeScript/ffi/jni/napi/jni/JEnv.h index 597cc637..b7eafa88 100644 --- a/NativeScript/ffi/jni/napi/jni/JEnv.h +++ b/NativeScript/ffi/jni/napi/jni/JEnv.h @@ -8,7 +8,7 @@ namespace tns { class JEnv { public: - JEnv() : m_env(s_threadEnv != nullptr ? s_threadEnv : GetEnvSlow()) {} + JEnv() : m_env(CachedOrSlowEnv()) {} JEnv(JNIEnv *jniEnv) : m_env(jniEnv != nullptr ? jniEnv : JEnv().m_env) {} @@ -451,17 +451,24 @@ namespace tns { static void UnpinThreadEnv(); + private: + struct ThreadEnv { + JNIEnv *env = nullptr; + bool pinned = false; + }; + + public: class EntryScope { public: - explicit EntryScope(JNIEnv *env) : m_active(!s_threadEnvPinned), m_previous(s_threadEnv) { + explicit EntryScope(JNIEnv *env) : m_thread(s_thread), m_active(!m_thread.pinned), m_previous(m_thread.env) { if (m_active) { - s_threadEnv = env; + m_thread.env = env; } } ~EntryScope() { - if (m_active && !s_threadEnvPinned) { - s_threadEnv = m_previous; + if (m_active && !m_thread.pinned) { + m_thread.env = m_previous; } } @@ -470,6 +477,7 @@ namespace tns { EntryScope &operator=(const EntryScope &) = delete; private: + ThreadEnv &m_thread; bool m_active; JNIEnv *m_previous; }; @@ -477,12 +485,16 @@ namespace tns { private: static JNIEnv *GetEnvSlow(); + static JNIEnv *CachedOrSlowEnv() { + JNIEnv *env = s_thread.env; + return env != nullptr ? env : GetEnvSlow(); + } + void CheckForJavaException(); JNIEnv *m_env; - static thread_local JNIEnv *s_threadEnv; - static thread_local bool s_threadEnvPinned; + static thread_local ThreadEnv s_thread; static JavaVM *s_jvm; From 4d4c29011e57b18328822092dab25851068f09d7 Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 09:41:22 +0500 Subject: [PATCH 03/16] perf(android): resolve cached method signatures without allocating --- .../jsi/callbackhandlers/CallbackHandlers.cpp | 26 ++--- .../ffi/jni/jsi/metadata/MethodCache.cpp | 4 +- .../ffi/jni/jsi/metadata/MethodCache.h | 108 +++++++++--------- .../callbackhandlers/CallbackHandlers.cpp | 26 ++--- .../ffi/jni/napi/metadata/MethodCache.cpp | 4 +- .../ffi/jni/napi/metadata/MethodCache.h | 107 +++++++++-------- 6 files changed, 136 insertions(+), 139 deletions(-) diff --git a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp index 4ed7e808..df86b156 100644 --- a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp @@ -164,10 +164,10 @@ JsValue CallbackHandlers::CallJavaMethod(JsRuntime &rt, const JsValue &caller, c JEnv jEnv; jclass clazz; jmethodID mid; - string *sig = nullptr; - string *returnType = nullptr; + const string *sig = nullptr; + const string *returnType = nullptr; auto retType = MethodReturnType::Unknown; - MethodCache::CacheMethodInfo mi; + const MethodCache::CacheMethodInfo *mi = nullptr; bool isSuper = false; if (metadataSignatureIsUnambiguous && entry != nullptr && @@ -287,8 +287,8 @@ JsValue CallbackHandlers::CallJavaMethod(JsRuntime &rt, const JsValue &caller, c clazz = jEnv.FindClass(className); if (clazz != nullptr) { - mi = MethodCache::ResolveMethodSignature(rt, className, methodName, argc, argv, isStatic); - if (mi.mid == nullptr) { + mi = &MethodCache::ResolveMethodSignature(rt, className, methodName, argc, argv, isStatic); + if (mi->mid == nullptr) { DEBUG_WRITE("Cannot resolve class=%s, method=%s, isStatic=%d, isSuper=%d", className.c_str(), methodName.c_str(), isStatic, isSuper); return js_util::undefined(); @@ -298,9 +298,9 @@ JsValue CallbackHandlers::CallJavaMethod(JsRuntime &rt, const JsValue &caller, c const string callerClassName = callerNode->GetName(); DEBUG_WRITE("Resolving method on caller class: %s.%s on className %s", callerClassName.c_str(), methodName.c_str(), className.c_str()); - mi = MethodCache::ResolveMethodSignature(rt, callerClassName, methodName, argc, argv, + mi = &MethodCache::ResolveMethodSignature(rt, callerClassName, methodName, argc, argv, isStatic); - if (mi.mid == nullptr) { + if (mi->mid == nullptr) { DEBUG_WRITE( "Cannot resolve class=%s, method=%s, isStatic=%d, isSuper=%d, callerClass=%s", className.c_str(), methodName.c_str(), isStatic, isSuper, @@ -309,11 +309,11 @@ JsValue CallbackHandlers::CallJavaMethod(JsRuntime &rt, const JsValue &caller, c } } - clazz = mi.clazz; - mid = mi.mid; - sig = &mi.signature; - returnType = &mi.returnType; - retType = mi.retType; + clazz = mi->clazz; + mid = mi->mid; + sig = &mi->signature; + returnType = &mi->returnType; + retType = mi->retType; } if (!isStatic) { @@ -562,7 +562,7 @@ bool CallbackHandlers::RegisterInstance(JsRuntime &rt, const JsValue &jsObject, objectManager->Link(jsObject, javaObjectID, nullptr, node); // resolve constructor - auto mi = MethodCache::ResolveConstructorSignature(rt, argWrapper, fullClassName, + const auto &mi = MethodCache::ResolveConstructorSignature(rt, argWrapper, fullClassName, generatedJavaClass, isInterface); // while the "instance" is being created, if an exception is thrown during the construction diff --git a/NativeScript/ffi/jni/jsi/metadata/MethodCache.cpp b/NativeScript/ffi/jni/jsi/metadata/MethodCache.cpp index 24a1f0f4..0c7f0813 100644 --- a/NativeScript/ffi/jni/jsi/metadata/MethodCache.cpp +++ b/NativeScript/ffi/jni/jsi/metadata/MethodCache.cpp @@ -28,7 +28,9 @@ void MethodCache::Init() } -robin_hood::unordered_map MethodCache::s_method_ctor_signature_cache; +robin_hood::unordered_node_map MethodCache::s_method_ctor_signature_cache; +thread_local string MethodCache::s_signatureKey; +const MethodCache::CacheMethodInfo MethodCache::s_unresolved; jclass MethodCache::RUNTIME_CLASS = nullptr; jmethodID MethodCache::RESOLVE_METHOD_OVERLOAD_METHOD_ID = nullptr; jmethodID MethodCache::RESOLVE_CONSTRUCTOR_SIGNATURE_ID = nullptr; diff --git a/NativeScript/ffi/jni/jsi/metadata/MethodCache.h b/NativeScript/ffi/jni/jsi/metadata/MethodCache.h index b0eddc66..30b70d0d 100644 --- a/NativeScript/ffi/jni/jsi/metadata/MethodCache.h +++ b/NativeScript/ffi/jni/jsi/metadata/MethodCache.h @@ -39,73 +39,69 @@ class MethodCache { static void Init(); - inline static MethodCache::CacheMethodInfo ResolveMethodSignature(JsRuntime &rt, const string &className, const string &methodName, size_t argc, const JsValue* argv, bool isStatic) + inline static const CacheMethodInfo &ResolveMethodSignature(JsRuntime &rt, const string &className, const string &methodName, size_t argc, const JsValue* argv, bool isStatic) { - CacheMethodInfo method_info; - - auto encoded_method_signature = EncodeSignature(rt, className, methodName, argc, argv, isStatic); - auto it = s_method_ctor_signature_cache.find(encoded_method_signature); + EncodeSignature(s_signatureKey, rt, className, methodName, argc, argv, isStatic); + auto it = s_method_ctor_signature_cache.find(s_signatureKey); - if (it == s_method_ctor_signature_cache.end()) + if (it != s_method_ctor_signature_cache.end()) { - auto signature = ResolveJavaMethod(rt, argc, argv, className, methodName); + return it->second; + } - DEBUG_WRITE("ResolveMethodSignature %s='%s'", encoded_method_signature.c_str(), signature.c_str()); + std::string encoded_method_signature = s_signatureKey; + auto signature = ResolveJavaMethod(rt, argc, argv, className, methodName); - if (!signature.empty()) - { - JEnv jEnv; - auto clazz = jEnv.FindClass(className); - assert(clazz != nullptr); - method_info.clazz = clazz; - method_info.signature = signature; - method_info.returnType = MetadataReader::ParseReturnType(method_info.signature); - method_info.retType = MetadataReader::GetReturnType(method_info.returnType); - method_info.isStatic = isStatic; - method_info.mid = isStatic - ? jEnv.GetStaticMethodID(clazz, methodName, signature) - : jEnv.GetMethodID(clazz, methodName, signature); - - s_method_ctor_signature_cache.emplace(encoded_method_signature, method_info); - } - } - else + DEBUG_WRITE("ResolveMethodSignature %s='%s'", encoded_method_signature.c_str(), signature.c_str()); + + if (signature.empty()) { - method_info = (*it).second; + return s_unresolved; } - return method_info; + CacheMethodInfo method_info; + JEnv jEnv; + auto clazz = jEnv.FindClass(className); + assert(clazz != nullptr); + method_info.clazz = clazz; + method_info.signature = signature; + method_info.returnType = MetadataReader::ParseReturnType(method_info.signature); + method_info.retType = MetadataReader::GetReturnType(method_info.returnType); + method_info.isStatic = isStatic; + method_info.mid = isStatic + ? jEnv.GetStaticMethodID(clazz, methodName, signature) + : jEnv.GetMethodID(clazz, methodName, signature); + + return s_method_ctor_signature_cache.emplace(encoded_method_signature, method_info).first->second; } - inline static MethodCache::CacheMethodInfo ResolveConstructorSignature(JsRuntime &rt, const ArgsWrapper &argWrapper, const string &fullClassName, jclass javaClass, bool isInterface) + inline static const CacheMethodInfo &ResolveConstructorSignature(JsRuntime &rt, const ArgsWrapper &argWrapper, const string &fullClassName, jclass javaClass, bool isInterface) { - CacheMethodInfo constructor_info; - - auto encoded_ctor_signature = EncodeSignature(rt, fullClassName, "", argWrapper.argc, argWrapper.argv, false); - auto it = s_method_ctor_signature_cache.find(encoded_ctor_signature); + EncodeSignature(s_signatureKey, rt, fullClassName, "", argWrapper.argc, argWrapper.argv, false); + auto it = s_method_ctor_signature_cache.find(s_signatureKey); - if (it == s_method_ctor_signature_cache.end()) + if (it != s_method_ctor_signature_cache.end()) { - auto signature = ResolveConstructor(rt, argWrapper.argc, argWrapper.argv, javaClass, isInterface); + return it->second; + } - DEBUG_WRITE("ResolveConstructorSignature %s='%s'", encoded_ctor_signature.c_str(), signature.c_str()); + std::string encoded_ctor_signature = s_signatureKey; + auto signature = ResolveConstructor(rt, argWrapper.argc, argWrapper.argv, javaClass, isInterface); - if (!signature.empty()) - { - JEnv jEnv; - constructor_info.clazz = javaClass; - constructor_info.signature = signature; - constructor_info.mid = jEnv.GetMethodID(javaClass, "", signature); + DEBUG_WRITE("ResolveConstructorSignature %s='%s'", encoded_ctor_signature.c_str(), signature.c_str()); - s_method_ctor_signature_cache.emplace(encoded_ctor_signature, constructor_info); - } - } - else + if (signature.empty()) { - constructor_info = (*it).second; + return s_unresolved; } - return constructor_info; + CacheMethodInfo constructor_info; + JEnv jEnv; + constructor_info.clazz = javaClass; + constructor_info.signature = signature; + constructor_info.mid = jEnv.GetMethodID(javaClass, "", signature); + + return s_method_ctor_signature_cache.emplace(encoded_ctor_signature, constructor_info).first->second; } private: @@ -113,9 +109,9 @@ class MethodCache { } // Encoded signature .S/I....<...> - inline static string EncodeSignature(JsRuntime &rt, const string &className, const string &methodName, size_t argc, const JsValue* argv, bool isStatic) + inline static void EncodeSignature(string &sig, JsRuntime &rt, const string &className, const string &methodName, size_t argc, const JsValue* argv, bool isStatic) { - string sig(className); + sig.assign(className); sig.append("."); if (isStatic) { @@ -128,17 +124,13 @@ class MethodCache { sig.append(methodName); sig.append("."); - stringstream s; - s << argc; - sig.append(s.str()); + sig.append(std::to_string(argc)); for (size_t i = 0; i < argc; i++) { sig.append("."); sig.append(GetType(rt, argv[i])); } - - return sig; } inline static string GetType(JsRuntime &rt, const JsValue &value) @@ -344,7 +336,11 @@ class MethodCache { * Used for caching the resolved constructor or method signature. * The encoded signature has template: .S/I....<...> */ - static robin_hood::unordered_map s_method_ctor_signature_cache; + static robin_hood::unordered_node_map s_method_ctor_signature_cache; + + static thread_local std::string s_signatureKey; + + static const CacheMethodInfo s_unresolved; }; } diff --git a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp index c39afb84..19a42b13 100644 --- a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp @@ -149,10 +149,10 @@ napi_value CallbackHandlers::CallJavaMethod(napi_env env, napi_value caller, con JEnv jEnv; jclass clazz; jmethodID mid; - string *sig = nullptr; - string *returnType = nullptr; + const string *sig = nullptr; + const string *returnType = nullptr; auto retType = MethodReturnType::Unknown; - MethodCache::CacheMethodInfo mi; + const MethodCache::CacheMethodInfo *mi = nullptr; bool isSuper = false; napi_status status; @@ -274,8 +274,8 @@ napi_value CallbackHandlers::CallJavaMethod(napi_env env, napi_value caller, con clazz = jEnv.FindClass(className); if (clazz != nullptr) { - mi = MethodCache::ResolveMethodSignature(env, className, methodName, argc, argv, isStatic); - if (mi.mid == nullptr) { + mi = &MethodCache::ResolveMethodSignature(env, className, methodName, argc, argv, isStatic); + if (mi->mid == nullptr) { DEBUG_WRITE("Cannot resolve class=%s, method=%s, isStatic=%d, isSuper=%d", className.c_str(), methodName.c_str(), isStatic, isSuper); return nullptr; @@ -285,9 +285,9 @@ napi_value CallbackHandlers::CallJavaMethod(napi_env env, napi_value caller, con const string callerClassName = callerNode->GetName(); DEBUG_WRITE("Resolving method on caller class: %s.%s on className %s", callerClassName.c_str(), methodName.c_str(), className.c_str()); - mi = MethodCache::ResolveMethodSignature(env, callerClassName, methodName, argc, argv, + mi = &MethodCache::ResolveMethodSignature(env, callerClassName, methodName, argc, argv, isStatic); - if (mi.mid == nullptr) { + if (mi->mid == nullptr) { DEBUG_WRITE( "Cannot resolve class=%s, method=%s, isStatic=%d, isSuper=%d, callerClass=%s", className.c_str(), methodName.c_str(), isStatic, isSuper, @@ -296,11 +296,11 @@ napi_value CallbackHandlers::CallJavaMethod(napi_env env, napi_value caller, con } } - clazz = mi.clazz; - mid = mi.mid; - sig = &mi.signature; - returnType = &mi.returnType; - retType = mi.retType; + clazz = mi->clazz; + mid = mi->mid; + sig = &mi->signature; + returnType = &mi->returnType; + retType = mi->retType; } @@ -573,7 +573,7 @@ bool CallbackHandlers::RegisterInstance(napi_env env, napi_value jsObject, objectManager->Link(jsObject, javaObjectID, nullptr, node); // resolve constructor - auto mi = MethodCache::ResolveConstructorSignature(env, argWrapper, fullClassName, + const auto &mi = MethodCache::ResolveConstructorSignature(env, argWrapper, fullClassName, generatedJavaClass, isInterface); // while the "instance" is being created, if an exception is thrown during the construction diff --git a/NativeScript/ffi/jni/napi/metadata/MethodCache.cpp b/NativeScript/ffi/jni/napi/metadata/MethodCache.cpp index 24a1f0f4..0c7f0813 100644 --- a/NativeScript/ffi/jni/napi/metadata/MethodCache.cpp +++ b/NativeScript/ffi/jni/napi/metadata/MethodCache.cpp @@ -28,7 +28,9 @@ void MethodCache::Init() } -robin_hood::unordered_map MethodCache::s_method_ctor_signature_cache; +robin_hood::unordered_node_map MethodCache::s_method_ctor_signature_cache; +thread_local string MethodCache::s_signatureKey; +const MethodCache::CacheMethodInfo MethodCache::s_unresolved; jclass MethodCache::RUNTIME_CLASS = nullptr; jmethodID MethodCache::RESOLVE_METHOD_OVERLOAD_METHOD_ID = nullptr; jmethodID MethodCache::RESOLVE_CONSTRUCTOR_SIGNATURE_ID = nullptr; diff --git a/NativeScript/ffi/jni/napi/metadata/MethodCache.h b/NativeScript/ffi/jni/napi/metadata/MethodCache.h index a573d247..93f35970 100644 --- a/NativeScript/ffi/jni/napi/metadata/MethodCache.h +++ b/NativeScript/ffi/jni/napi/metadata/MethodCache.h @@ -39,72 +39,69 @@ class MethodCache { static void Init(); - inline static MethodCache::CacheMethodInfo ResolveMethodSignature(napi_env env, const string &className, const string &methodName, size_t argc, napi_value* argv, bool isStatic) + inline static const CacheMethodInfo &ResolveMethodSignature(napi_env env, const string &className, const string &methodName, size_t argc, napi_value* argv, bool isStatic) { - CacheMethodInfo method_info; - auto encoded_method_signature = EncodeSignature(env, className, methodName,argc, argv, isStatic); - auto it = s_method_ctor_signature_cache.find(encoded_method_signature); + EncodeSignature(s_signatureKey, env, className, methodName, argc, argv, isStatic); + auto it = s_method_ctor_signature_cache.find(s_signatureKey); - if (it == s_method_ctor_signature_cache.end()) + if (it != s_method_ctor_signature_cache.end()) { - auto signature = ResolveJavaMethod(env, argc, argv, className, methodName); + return it->second; + } - DEBUG_WRITE("ResolveMethodSignature %s='%s'", encoded_method_signature.c_str(), signature.c_str()); + std::string encoded_method_signature = s_signatureKey; + auto signature = ResolveJavaMethod(env, argc, argv, className, methodName); - if (!signature.empty()) - { - JEnv jEnv; - auto clazz = jEnv.FindClass(className); - assert(clazz != nullptr); - method_info.clazz = clazz; - method_info.signature = signature; - method_info.returnType = MetadataReader::ParseReturnType(method_info.signature); - method_info.retType = MetadataReader::GetReturnType(method_info.returnType); - method_info.isStatic = isStatic; - method_info.mid = isStatic - ? jEnv.GetStaticMethodID(clazz, methodName, signature) - : jEnv.GetMethodID(clazz, methodName, signature); - - s_method_ctor_signature_cache.emplace(encoded_method_signature, method_info); - } - } - else + DEBUG_WRITE("ResolveMethodSignature %s='%s'", encoded_method_signature.c_str(), signature.c_str()); + + if (signature.empty()) { - method_info = (*it).second; + return s_unresolved; } - return method_info; + CacheMethodInfo method_info; + JEnv jEnv; + auto clazz = jEnv.FindClass(className); + assert(clazz != nullptr); + method_info.clazz = clazz; + method_info.signature = signature; + method_info.returnType = MetadataReader::ParseReturnType(method_info.signature); + method_info.retType = MetadataReader::GetReturnType(method_info.returnType); + method_info.isStatic = isStatic; + method_info.mid = isStatic + ? jEnv.GetStaticMethodID(clazz, methodName, signature) + : jEnv.GetMethodID(clazz, methodName, signature); + + return s_method_ctor_signature_cache.emplace(encoded_method_signature, method_info).first->second; } - inline static MethodCache::CacheMethodInfo ResolveConstructorSignature(napi_env env, const ArgsWrapper &argWrapper, const string &fullClassName, jclass javaClass, bool isInterface) + inline static const CacheMethodInfo &ResolveConstructorSignature(napi_env env, const ArgsWrapper &argWrapper, const string &fullClassName, jclass javaClass, bool isInterface) { - CacheMethodInfo constructor_info; - - auto encoded_ctor_signature = EncodeSignature(env, fullClassName, "", argWrapper.argc, argWrapper.argv, false); - auto it = s_method_ctor_signature_cache.find(encoded_ctor_signature); + EncodeSignature(s_signatureKey, env, fullClassName, "", argWrapper.argc, argWrapper.argv, false); + auto it = s_method_ctor_signature_cache.find(s_signatureKey); - if (it == s_method_ctor_signature_cache.end()) + if (it != s_method_ctor_signature_cache.end()) { - auto signature = ResolveConstructor(env, argWrapper.argc, argWrapper.argv, javaClass, isInterface); + return it->second; + } - DEBUG_WRITE("ResolveConstructorSignature %s='%s'", encoded_ctor_signature.c_str(), signature.c_str()); + std::string encoded_ctor_signature = s_signatureKey; + auto signature = ResolveConstructor(env, argWrapper.argc, argWrapper.argv, javaClass, isInterface); - if (!signature.empty()) - { - JEnv jEnv; - constructor_info.clazz = javaClass; - constructor_info.signature = signature; - constructor_info.mid = jEnv.GetMethodID(javaClass, "", signature); + DEBUG_WRITE("ResolveConstructorSignature %s='%s'", encoded_ctor_signature.c_str(), signature.c_str()); - s_method_ctor_signature_cache.emplace(encoded_ctor_signature, constructor_info); - } - } - else + if (signature.empty()) { - constructor_info = (*it).second; + return s_unresolved; } - return constructor_info; + CacheMethodInfo constructor_info; + JEnv jEnv; + constructor_info.clazz = javaClass; + constructor_info.signature = signature; + constructor_info.mid = jEnv.GetMethodID(javaClass, "", signature); + + return s_method_ctor_signature_cache.emplace(encoded_ctor_signature, constructor_info).first->second; } private: @@ -112,9 +109,9 @@ class MethodCache { } // Encoded signature .S/I....<...> - inline static string EncodeSignature(napi_env env, const string &className, const string &methodName, size_t argc, napi_value* argv, bool isStatic) + inline static void EncodeSignature(string &sig, napi_env env, const string &className, const string &methodName, size_t argc, napi_value* argv, bool isStatic) { - string sig(className); + sig.assign(className); sig.append("."); if (isStatic) { @@ -127,17 +124,13 @@ class MethodCache { sig.append(methodName); sig.append("."); - stringstream s; - s << argc; - sig.append(s.str()); + sig.append(std::to_string(argc)); for (int i = 0; i < argc; i++) { sig.append("."); sig.append(GetType(env, argv[i])); } - - return sig; } inline static string GetType(napi_env env, napi_value value) @@ -365,7 +358,11 @@ class MethodCache { * Used for caching the resolved constructor or method signature. * The encoded signature has template: .S/I....<...> */ - static robin_hood::unordered_map s_method_ctor_signature_cache; + static robin_hood::unordered_node_map s_method_ctor_signature_cache; + + static thread_local std::string s_signatureKey; + + static const CacheMethodInfo s_unresolved; }; } From da925f05a2fa8a9f59882e8ffd99c46b8fcd5ce7 Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 09:41:46 +0500 Subject: [PATCH 04/16] perf(android): look up a base method's counterpart by name hash --- .../ffi/jni/jsi/metadata/MetadataNode.cpp | 16 +++++++++------- .../ffi/jni/napi/metadata/MetadataNode.cpp | 16 +++++++++------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp b/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp index de813870..551161a7 100644 --- a/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp +++ b/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp @@ -1221,6 +1221,12 @@ std::vector MetadataNode::SetClassMembersFro robin_hood::unordered_map collectedExtensionMethods; + robin_hood::unordered_flat_map baseMethodsByName; + baseMethodsByName.reserve(baseInstanceMethodsCallbackData.size()); + for (auto baseMethod: baseInstanceMethodsCallbackData) { + baseMethodsByName.emplace(baseMethod->candidates.front().name, baseMethod); + } + auto prototype = constructor.getPropertyAsObject(rt, "prototype"); // The napi tree also took a strong reference to the prototype here, for the @@ -1291,13 +1297,9 @@ std::vector MetadataNode::SetClassMembersFro instanceMethodData.push_back(callbackData); instanceMethodsCallbackData.push_back(callbackData); - auto itFound = std::find_if(baseInstanceMethodsCallbackData.begin(), - baseInstanceMethodsCallbackData.end(), - [&methodName](MethodCallbackData *x) { - return x->candidates.front().name == methodName; - }); - if (itFound != baseInstanceMethodsCallbackData.end()) { - callbackData->parent = *itFound; + auto itFound = baseMethodsByName.find(std::string_view(methodName)); + if (itFound != baseMethodsByName.end()) { + callbackData->parent = itFound->second; } lastMethodName = methodName; diff --git a/NativeScript/ffi/jni/napi/metadata/MetadataNode.cpp b/NativeScript/ffi/jni/napi/metadata/MetadataNode.cpp index cd123bd5..ac10b824 100644 --- a/NativeScript/ffi/jni/napi/metadata/MetadataNode.cpp +++ b/NativeScript/ffi/jni/napi/metadata/MetadataNode.cpp @@ -1513,6 +1513,12 @@ std::vector MetadataNode::SetClassMembersFro robin_hood::unordered_map collectedExtensionMethods; + robin_hood::unordered_flat_map baseMethodsByName; + baseMethodsByName.reserve(baseInstanceMethodsCallbackData.size()); + for (auto baseMethod: baseInstanceMethodsCallbackData) { + baseMethodsByName.emplace(baseMethod->candidates.front().name, baseMethod); + } + napi_value prototype = napi_util::get_prototype(env, constructor); // Strong reference to the prototype shared by every instance field/property @@ -1579,13 +1585,9 @@ std::vector MetadataNode::SetClassMembersFro instanceMethodData.push_back(callbackData); instanceMethodsCallbackData.push_back(callbackData); - auto itFound = std::find_if(baseInstanceMethodsCallbackData.begin(), - baseInstanceMethodsCallbackData.end(), - [&methodName](MethodCallbackData *x) { - return x->candidates.front().name == methodName; - }); - if (itFound != baseInstanceMethodsCallbackData.end()) { - callbackData->parent = *itFound; + auto itFound = baseMethodsByName.find(std::string_view(methodName)); + if (itFound != baseMethodsByName.end()) { + callbackData->parent = itFound->second; } lastMethodName = methodName; From 3f389a462498325174650183f79b80b8c21d7c4b Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 09:43:29 +0500 Subject: [PATCH 05/16] perf(android): pack the call argument type ids into the values array --- .../jsi/callbackhandlers/CallbackHandlers.cpp | 2 +- .../ffi/jni/jsi/conversion/ArgConverter.cpp | 18 +++------- .../ffi/jni/jsi/conversion/ArgConverter.h | 2 -- .../ffi/jni/jsi/conversion/JavaCallArgs.h | 12 +++++-- .../callbackhandlers/CallbackHandlers.cpp | 2 +- .../ffi/jni/napi/conversion/ArgConverter.cpp | 18 +++------- .../ffi/jni/napi/conversion/ArgConverter.h | 2 -- .../ffi/jni/napi/conversion/JavaCallArgs.h | 12 +++++-- .../runtime/android/jsi/com_tns_Runtime.cpp | 4 +-- .../runtime/android/napi/com_tns_Runtime.cpp | 4 +-- .../src/main/java/com/tns/Runtime.java | 34 ++++++++++--------- 11 files changed, 52 insertions(+), 58 deletions(-) diff --git a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp index df86b156..a5218b37 100644 --- a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp @@ -1161,7 +1161,7 @@ JsValue CallbackHandlers::CallJSMethod(JsRuntime &rt, JNIEnv *_jEnv, // a throw. engine:: propagates a JS throw as a JSError, so the equivalent is // to let it unwind and convert it here. try { - int argc = ArgConverter::GetJavaArgsLength(jEnv, args); + int argc = args.count; if (argc > 0) { JsValue *jsArgs = nullptr; JsValue stack_args[8]; diff --git a/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp b/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp index 54ccfa02..9781597f 100644 --- a/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp +++ b/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp @@ -139,31 +139,21 @@ JsValue ArgConverter::NativeScriptLongFunctionCallback(JsRuntime &rt, const JsVa } } -int ArgConverter::GetJavaArgsLength(JNIEnv *env, const JavaCallArgs &args) { - return args.types == nullptr ? 0 : env->GetArrayLength(args.types); -} - void ArgConverter::ConvertJavaArgsToJsArgs(JsRuntime &rt, const JavaCallArgs &args, size_t argc, JsValue *arr) { JEnv jenv; constexpr size_t kInlineArgs = 16; - jint inlineTypes[kInlineArgs]; - jlong inlineValues[kInlineArgs]; - std::vector heapTypes; + jlong inlineValues[JavaCallArgs::PackedLength(kInlineArgs)]; std::vector heapValues; - jint *types = inlineTypes; jlong *values = inlineValues; if (argc > kInlineArgs) { - heapTypes.resize(argc); - heapValues.resize(argc); - types = heapTypes.data(); + heapValues.resize(JavaCallArgs::PackedLength(argc)); values = heapValues.data(); } JNIEnv *jni = jenv; - jni->GetIntArrayRegion(args.types, 0, argc, types); - jni->GetLongArrayRegion(args.values, 0, argc, values); + jni->GetLongArrayRegion(args.values, 0, JavaCallArgs::PackedLength(argc), values); auto runtime = Runtime::GetRuntime(rt); auto objectManager = runtime->GetObjectManager(); @@ -171,7 +161,7 @@ void ArgConverter::ConvertJavaArgsToJsArgs(JsRuntime &rt, const JavaCallArgs &ar for (size_t i = 0; i < argc; i++) { jlong bits = values[i]; JsValue jsArg; - switch (static_cast(types[i])) { + switch (JavaCallArgs::TypeAt(values, argc, i)) { case Type::Boolean: jsArg = JsValue(bits != 0); break; diff --git a/NativeScript/ffi/jni/jsi/conversion/ArgConverter.h b/NativeScript/ffi/jni/jsi/conversion/ArgConverter.h index 9efc6b06..090de7c0 100644 --- a/NativeScript/ffi/jni/jsi/conversion/ArgConverter.h +++ b/NativeScript/ffi/jni/jsi/conversion/ArgConverter.h @@ -21,8 +21,6 @@ namespace tns { public: static void Init(JsRuntime &rt); - static int GetJavaArgsLength(JNIEnv *env, const JavaCallArgs &args); - static void ConvertJavaArgsToJsArgs(JsRuntime &rt, const JavaCallArgs &args, size_t length, JsValue *arr); diff --git a/NativeScript/ffi/jni/jsi/conversion/JavaCallArgs.h b/NativeScript/ffi/jni/jsi/conversion/JavaCallArgs.h index adb165c2..33d5f363 100644 --- a/NativeScript/ffi/jni/jsi/conversion/JavaCallArgs.h +++ b/NativeScript/ffi/jni/jsi/conversion/JavaCallArgs.h @@ -2,13 +2,21 @@ #define JAVACALLARGS_H_ #include "jni.h" +#include "JType.h" namespace tns { - // The arrays com.tns.Runtime.packageArgs builds for a Java -> JS call. struct JavaCallArgs { - jintArray types; + jint count; jlongArray values; jobjectArray refs; + + static constexpr int PackedLength(int count) { + return count + (count + 7) / 8; + } + + static Type TypeAt(const jlong *packed, int count, int i) { + return static_cast((packed[count + i / 8] >> ((i % 8) * 8)) & 0xff); + } }; } diff --git a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp index 19a42b13..6e04499f 100644 --- a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp @@ -1203,7 +1203,7 @@ napi_value CallbackHandlers::CallJSMethod(napi_env env, JNIEnv *_jEnv, bool exceptionPending; NAPI_GUARD(napi_is_exception_pending(env, &exceptionPending)) {} - int argc = ArgConverter::GetJavaArgsLength(jEnv, args); + int argc = args.count; if (argc > 0) { napi_value* jsArgs = nullptr; napi_value stack_args[8]; diff --git a/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp b/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp index a1e7aeb8..8fa827d0 100644 --- a/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp +++ b/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp @@ -185,31 +185,21 @@ napi_value ArgConverter::NativeScriptLongFunctionCallback(napi_env env, napi_cal return nullptr; } -int ArgConverter::GetJavaArgsLength(JNIEnv *env, const JavaCallArgs &args) { - return args.types == nullptr ? 0 : env->GetArrayLength(args.types); -} - void ArgConverter::ConvertJavaArgsToJsArgs(napi_env env, const JavaCallArgs &args, size_t argc, napi_value* arr) { napi_status status; JEnv jenv; constexpr size_t kInlineArgs = 16; - jint inlineTypes[kInlineArgs]; - jlong inlineValues[kInlineArgs]; - std::vector heapTypes; + jlong inlineValues[JavaCallArgs::PackedLength(kInlineArgs)]; std::vector heapValues; - jint *types = inlineTypes; jlong *values = inlineValues; if (argc > kInlineArgs) { - heapTypes.resize(argc); - heapValues.resize(argc); - types = heapTypes.data(); + heapValues.resize(JavaCallArgs::PackedLength(argc)); values = heapValues.data(); } JNIEnv *jni = jenv; - jni->GetIntArrayRegion(args.types, 0, argc, types); - jni->GetLongArrayRegion(args.values, 0, argc, values); + jni->GetLongArrayRegion(args.values, 0, JavaCallArgs::PackedLength(argc), values); auto runtime = Runtime::GetRuntime(env); auto objectManager = runtime->GetObjectManager(); @@ -217,7 +207,7 @@ void ArgConverter::ConvertJavaArgsToJsArgs(napi_env env, const JavaCallArgs &arg for (size_t i = 0; i < argc; i++) { jlong bits = values[i]; napi_value jsArg; - switch (static_cast(types[i])) { + switch (JavaCallArgs::TypeAt(values, argc, i)) { case Type::Boolean: NAPI_GUARD(napi_get_boolean(env, bits != 0, &jsArg)) {} break; diff --git a/NativeScript/ffi/jni/napi/conversion/ArgConverter.h b/NativeScript/ffi/jni/napi/conversion/ArgConverter.h index 7bf6f947..d739c909 100644 --- a/NativeScript/ffi/jni/napi/conversion/ArgConverter.h +++ b/NativeScript/ffi/jni/napi/conversion/ArgConverter.h @@ -21,8 +21,6 @@ namespace tns { public: static void Init(napi_env env); - static int GetJavaArgsLength(JNIEnv *env, const JavaCallArgs &args); - static void ConvertJavaArgsToJsArgs(napi_env env, const JavaCallArgs &args, size_t length, napi_value* arr); static napi_value ConvertFromJavaLong(napi_env env, jlong value); diff --git a/NativeScript/ffi/jni/napi/conversion/JavaCallArgs.h b/NativeScript/ffi/jni/napi/conversion/JavaCallArgs.h index adb165c2..33d5f363 100644 --- a/NativeScript/ffi/jni/napi/conversion/JavaCallArgs.h +++ b/NativeScript/ffi/jni/napi/conversion/JavaCallArgs.h @@ -2,13 +2,21 @@ #define JAVACALLARGS_H_ #include "jni.h" +#include "JType.h" namespace tns { - // The arrays com.tns.Runtime.packageArgs builds for a Java -> JS call. struct JavaCallArgs { - jintArray types; + jint count; jlongArray values; jobjectArray refs; + + static constexpr int PackedLength(int count) { + return count + (count + 7) / 8; + } + + static Type TypeAt(const jlong *packed, int count, int i) { + return static_cast((packed[count + i / 8] >> ((i % 8) * 8)) & 0xff); + } }; } diff --git a/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp b/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp index 63cd3f55..29e12b0f 100644 --- a/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp +++ b/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp @@ -200,7 +200,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_runScript(JNIEnv* _env, jobjec #endif -extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName,jint retType, jboolean isConstructor, jintArray argTypes, jlongArray argValues, jobjectArray argRefs) { +extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName,jint retType, jboolean isConstructor, jint argCount, jlongArray argValues, jobjectArray argRefs) { JEnv::EntryScope envScope(_env); jobject result = nullptr; auto runtime = TryGetRuntime(runtimeId); @@ -208,7 +208,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en JSScope scope(runtime->GetEngineHost()); try { - result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, retType, isConstructor, JavaCallArgs{argTypes, argValues, argRefs}); + result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, retType, isConstructor, JavaCallArgs{argCount, argValues, argRefs}); } catch (NativeScriptException& e) { e.ReThrowToJava(&runtime->GetJSRuntime()); } catch (std::exception e) { diff --git a/NativeScript/runtime/android/napi/com_tns_Runtime.cpp b/NativeScript/runtime/android/napi/com_tns_Runtime.cpp index 1ad9db98..cd94f070 100644 --- a/NativeScript/runtime/android/napi/com_tns_Runtime.cpp +++ b/NativeScript/runtime/android/napi/com_tns_Runtime.cpp @@ -180,7 +180,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_runScript(JNIEnv* _env, jobjec return result; } -extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName,jint retType, jboolean isConstructor, jintArray argTypes, jlongArray argValues, jobjectArray argRefs) { +extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName,jint retType, jboolean isConstructor, jint argCount, jlongArray argValues, jobjectArray argRefs) { JEnv::EntryScope envScope(_env); jobject result = nullptr; auto runtime = TryGetRuntime(runtimeId); @@ -188,7 +188,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en NapiScope scope(runtime->GetNapiEnv()); try { - result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, retType, isConstructor, JavaCallArgs{argTypes, argValues, argRefs}); + result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, retType, isConstructor, JavaCallArgs{argCount, argValues, argRefs}); } catch (NativeScriptException& e) { e.ReThrowToJava( runtime->GetNapiEnv()); } catch (std::exception e) { diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java index f1eb1409..f7377662 100644 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -60,7 +60,7 @@ private native void attachNativeScript(int runtimeId, String metadataPath, long private native Object runScript(int runtimeId, String filePath) throws NativeScriptException; - private native Object callJSMethodNative(int runtimeId, int javaObjectID, Class claz, String methodName, int retType, boolean isConstructor, int[] argTypes, long[] argValues, Object[] argRefs) throws NativeScriptException; + private native Object callJSMethodNative(int runtimeId, int javaObjectID, Class claz, String methodName, int retType, boolean isConstructor, int argCount, long[] argValues, Object[] argRefs) throws NativeScriptException; private native void createJSInstanceNative(int runtimeId, Object javaObject, int javaObjectID, String canonicalName); @@ -1264,14 +1264,15 @@ private Object callJSMethodImpl(Integer javaObjectID, Object javaObject, String } private static final class PackagedArgs { - int[] types; + int count; long[] values; Object[] refs; } - // Packages args as parallel arrays: the type id and the raw bits of each primitive, plus a - // reference only for strings (the string) and objects (the canonical class name). A javaObject - // with no javaObjectID, meaning javascript has no object for it yet, is assigned one. + // Packages args as one long[]: count raw values (the bits of a primitive, an object's id), + // then one type id per byte, eight to a slot. A reference is kept only for strings (the + // string) and objects (the canonical class name). A javaObject with no javaObjectID, + // meaning javascript has no object for it yet, is assigned one. private PackagedArgs packageArgs(Object... args) { PackagedArgs packaged = new PackagedArgs(); if (args == null || args.length == 0) { @@ -1279,24 +1280,25 @@ private PackagedArgs packageArgs(Object... args) { } int len = args.length; - packaged.types = new int[len]; - packaged.values = new long[len]; + packaged.count = len; + long[] values = new long[len + (len + 7) / 8]; + packaged.values = values; for (int i = 0; i < len; i++) { Object value = args[i]; int typeId = TypeIDs.GetObjectTypeId(value); - packaged.types[i] = typeId; + values[len + i / 8] |= ((long) typeId & 0xff) << ((i % 8) * 8); if (typeId == TypeIDs.Boolean) { - packaged.values[i] = ((Boolean) value) ? 1L : 0L; + values[i] = ((Boolean) value) ? 1L : 0L; } else if (typeId == TypeIDs.Char) { - packaged.values[i] = (Character) value; + values[i] = (Character) value; } else if (typeId == TypeIDs.Byte || typeId == TypeIDs.Short || typeId == TypeIDs.Int || typeId == TypeIDs.Long) { - packaged.values[i] = ((Number) value).longValue(); + values[i] = ((Number) value).longValue(); } else if (typeId == TypeIDs.Float) { - packaged.values[i] = Float.floatToRawIntBits((Float) value); + values[i] = Float.floatToRawIntBits((Float) value); } else if (typeId == TypeIDs.Double) { - packaged.values[i] = Double.doubleToRawLongBits((Double) value); + values[i] = Double.doubleToRawLongBits((Double) value); } else if (typeId == TypeIDs.string) { if (packaged.refs == null) { packaged.refs = new Object[len]; @@ -1307,7 +1309,7 @@ private PackagedArgs packageArgs(Object... args) { packaged.refs = new Object[len]; } packaged.refs[i] = value.getClass().getName(); - packaged.values[i] = getOrCreateJavaObjectID(value); + values[i] = getOrCreateJavaObjectID(value); } } @@ -1391,7 +1393,7 @@ private Object dispatchCallJSMethodNative(final int javaObjectID, Class claz, if (enableMultithreadedJavascript || isWorkThread) { PackagedArgs packagedArgs = packageArgs(tmpArgs); try { - ret = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, returnType, isConstructor, packagedArgs.types, packagedArgs.values, packagedArgs.refs); + ret = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, returnType, isConstructor, packagedArgs.count, packagedArgs.values, packagedArgs.refs); } catch (NativeScriptException e) { if (discardUncaughtJsExceptions) { String errorMessage = "Error on \"" + Thread.currentThread().getName() + "\" thread for callJSMethodNative\n"; @@ -1412,7 +1414,7 @@ public void run() { synchronized (this) { try { final PackagedArgs packagedArgs = packageArgs(tmpArgs); - arr[0] = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, returnType, isCtor, packagedArgs.types, packagedArgs.values, packagedArgs.refs); + arr[0] = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, returnType, isCtor, packagedArgs.count, packagedArgs.values, packagedArgs.refs); } catch (NativeScriptException e) { if (discardUncaughtJsExceptions) { String errorMessage = "Error on \"" + Thread.currentThread().getName() + "\" thread for callJSMethodNative\n"; From 288354b973a4eb1252c0d357e2c301a710d76303 Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 09:46:57 +0500 Subject: [PATCH 06/16] perf(android): keep Java objects in one id-indexed table instead of four maps --- .../java/com/tns/NativeScriptAbstractMap.java | 515 -------- .../java/com/tns/NativeScriptHashMap.java | 1056 ----------------- .../java/com/tns/NativeScriptWeakHashMap.java | 725 ----------- .../src/main/java/com/tns/ObjectTable.java | 481 ++++++++ .../src/main/java/com/tns/Runtime.java | 148 +-- .../test/java/com/tns/ObjectTableTest.java | 305 +++++ .../src/test/java/com/tns/RuntimeTest.java | 71 +- 7 files changed, 824 insertions(+), 2477 deletions(-) delete mode 100644 platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptAbstractMap.java delete mode 100644 platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptHashMap.java delete mode 100644 platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptWeakHashMap.java create mode 100644 platforms/android/test-app/runtime/src/main/java/com/tns/ObjectTable.java create mode 100644 platforms/android/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptAbstractMap.java b/platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptAbstractMap.java deleted file mode 100644 index 3de04826..00000000 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptAbstractMap.java +++ /dev/null @@ -1,515 +0,0 @@ -package com.tns; - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.io.Serializable; -import java.util.AbstractCollection; -import java.util.AbstractSet; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -/** - * A base class for {@code Map} implementations. - * - *

- * Subclasses that permit new mappings to be added must override {@link #put}. - * - *

- * The default implementations of many methods are inefficient for large maps. For example in the default implementation, each call to {@link #get} performs a linear iteration of the entry set. Subclasses should override such methods to improve their performance. - * - * @since 1.2 - */ -public abstract class NativeScriptAbstractMap implements Map { - // Lazily-initialized key set (for implementing {@link #keySet}). - Set keySet; - - // Lazily-initialized values collection (for implementing {@link #values}). - Collection valuesCollection; - - /** - * An immutable key-value mapping. Despite the name, this class is non-final - * and its subclasses may be mutable. - * - * @since 1.6 - */ - public static class SimpleImmutableEntry implements Map.Entry, Serializable { - private static final long serialVersionUID = 7138329143949025153L; - - private final K key; - private final V value; - - public SimpleImmutableEntry(K theKey, V theValue) { - key = theKey; - value = theValue; - } - - /** - * Constructs an instance with the key and value of {@code copyFrom}. - */ - public SimpleImmutableEntry(Map.Entry copyFrom) { - key = copyFrom.getKey(); - value = copyFrom.getValue(); - } - - public K getKey() { - return key; - } - - public V getValue() { - return value; - } - - /** - * This base implementation throws {@code UnsupportedOperationException} always. - */ - public V setValue(V object) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (object instanceof Map.Entry) { - Map.Entry entry = (Map.Entry) object; - return (key == null ? entry.getKey() == null : key.equals(entry.getKey())) && (value == null ? entry.getValue() == null : value.equals(entry.getValue())); - } - return false; - } - - @Override - public int hashCode() { - return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); - } - - @Override - public String toString() { - return key + "=" + value; - } - } - - /** - * A key-value mapping with mutable values. - * - * @since 1.6 - */ - public static class SimpleEntry implements Map.Entry, Serializable { - private static final long serialVersionUID = -8499721149061103585L; - - private final K key; - private V value; - - public SimpleEntry(K theKey, V theValue) { - key = theKey; - value = theValue; - } - - /** - * Constructs an instance with the key and value of {@code copyFrom}. - */ - public SimpleEntry(Map.Entry copyFrom) { - key = copyFrom.getKey(); - value = copyFrom.getValue(); - } - - public K getKey() { - return key; - } - - public V getValue() { - return value; - } - - public V setValue(V object) { - V result = value; - value = object; - return result; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (object instanceof Map.Entry) { - Map.Entry entry = (Map.Entry) object; - return (key == null ? entry.getKey() == null : key.equals(entry.getKey())) && (value == null ? entry.getValue() == null : value.equals(entry.getValue())); - } - return false; - } - - @Override - public int hashCode() { - return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); - } - - @Override - public String toString() { - return key + "=" + value; - } - } - - protected NativeScriptAbstractMap() { - } - - /** - * {@inheritDoc} - * - *

- * This implementation calls {@code entrySet().clear()}. - */ - public void clear() { - entrySet().clear(); - } - - /** - * {@inheritDoc} - * - *

- * This implementation iterates its key set, looking for a key that {@code key} equals. - */ - public boolean containsKey(Object key) { - Iterator> it = entrySet().iterator(); - if (key != null) { - while (it.hasNext()) { - if (key.equals(it.next().getKey())) { - return true; - } - } - } else { - while (it.hasNext()) { - if (it.next().getKey() == null) { - return true; - } - } - } - return false; - } - - /** - * {@inheritDoc} - * - *

- * This implementation iterates its entry set, looking for an entry with a value that {@code value} equals. - */ - public boolean containsValue(Object value) { - Iterator> it = entrySet().iterator(); - if (value != null) { - while (it.hasNext()) { - if (value.equals(it.next().getValue())) { - return true; - } - } - } else { - while (it.hasNext()) { - if (it.next().getValue() == null) { - return true; - } - } - } - return false; - } - - public abstract Set> entrySet(); - - /** - * {@inheritDoc} - * - *

- * This implementation first checks the structure of {@code object}. If it is not a map or of a different size, this returns false. Otherwise it iterates its own entry set, looking up each entry's key in {@code object} . If any value does not equal the other map's value for the same key, this returns false. Otherwise it returns true. - */ - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (object instanceof Map) { - Map map = (Map) object; - if (size() != map.size()) { - return false; - } - - try { - for (Entry entry : entrySet()) { - K key = entry.getKey(); - V mine = entry.getValue(); - Object theirs = map.get(key); - if (mine == null) { - if (theirs != null || !map.containsKey(key)) { - return false; - } - } else if (!mine.equals(theirs)) { - return false; - } - } - } catch (NullPointerException ignored) { - return false; - } catch (ClassCastException ignored) { - return false; - } - return true; - } - return false; - } - - /** - * {@inheritDoc} - * - *

- * This implementation iterates its entry set, looking for an entry with a key that {@code key} equals. - */ - public V get(Object key) { - Iterator> it = entrySet().iterator(); - if (key != null) { - while (it.hasNext()) { - Map.Entry entry = it.next(); - if (key.equals(entry.getKey())) { - return entry.getValue(); - } - } - } else { - while (it.hasNext()) { - Map.Entry entry = it.next(); - if (entry.getKey() == null) { - return entry.getValue(); - } - } - } - return null; - } - - /** - * {@inheritDoc} - * - *

- * This implementation iterates its entry set, summing the hashcodes of its entries. - */ - @Override - public int hashCode() { - int result = 0; - Iterator> it = entrySet().iterator(); - while (it.hasNext()) { - result += it.next().hashCode(); - } - return result; - } - - /** - * {@inheritDoc} - * - *

- * This implementation compares {@code size()} to 0. - */ - public boolean isEmpty() { - return size() == 0; - } - - /** - * {@inheritDoc} - * - *

- * This implementation returns a view that calls through this to map. Its iterator transforms this map's entry set iterator to return keys. - */ - public Set keySet() { - if (keySet == null) { - keySet = new AbstractSet() { - @Override - public boolean contains(Object object) { - return containsKey(object); - } - - @Override - public int size() { - return NativeScriptAbstractMap.this.size(); - } - - @Override - public Iterator iterator() { - return new Iterator() { - Iterator> setIterator = entrySet().iterator(); - - public boolean hasNext() { - return setIterator.hasNext(); - } - - public K next() { - return setIterator.next().getKey(); - } - - public void remove() { - setIterator.remove(); - } - }; - } - }; - } - return keySet; - } - - /** - * {@inheritDoc} - * - *

- * This base implementation throws {@code UnsupportedOperationException}. - */ - public V put(K key, V value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - * - *

- * This implementation iterates through {@code map}'s entry set, calling {@code put()} for each. - */ - public void putAll(Map map) { - for (Map.Entry entry : map.entrySet()) { - put(entry.getKey(), entry.getValue()); - } - } - - /** - * {@inheritDoc} - * - *

- * This implementation iterates its entry set, removing the entry with a key that {@code key} equals. - */ - public V remove(Object key) { - Iterator> it = entrySet().iterator(); - if (key != null) { - while (it.hasNext()) { - Map.Entry entry = it.next(); - if (key.equals(entry.getKey())) { - it.remove(); - return entry.getValue(); - } - } - } else { - while (it.hasNext()) { - Map.Entry entry = it.next(); - if (entry.getKey() == null) { - it.remove(); - return entry.getValue(); - } - } - } - return null; - } - - /** - * {@inheritDoc} - * - *

- * This implementation returns its entry set's size. - */ - public int size() { - return entrySet().size(); - } - - /** - * {@inheritDoc} - * - *

- * This implementation composes a string by iterating its entry set. If this map contains itself as a key or a value, the string "(this Map)" will appear in its place. - */ - @Override - public String toString() { - if (isEmpty()) { - return "{}"; - } - - StringBuilder buffer = new StringBuilder(size() * 28); - buffer.append('{'); - Iterator> it = entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = it.next(); - Object key = entry.getKey(); - if (key != this) { - buffer.append(key); - } else { - buffer.append("(this Map)"); - } - buffer.append('='); - Object value = entry.getValue(); - if (value != this) { - buffer.append(value); - } else { - buffer.append("(this Map)"); - } - if (it.hasNext()) { - buffer.append(", "); - } - } - buffer.append('}'); - return buffer.toString(); - } - - /** - * {@inheritDoc} - * - *

- * This implementation returns a view that calls through this to map. Its iterator transforms this map's entry set iterator to return values. - */ - public Collection values() { - if (valuesCollection == null) { - valuesCollection = new AbstractCollection() { - @Override - public int size() { - return NativeScriptAbstractMap.this.size(); - } - - @Override - public boolean contains(Object object) { - return containsValue(object); - } - - @Override - public Iterator iterator() { - return new Iterator() { - Iterator> setIterator = entrySet().iterator(); - - public boolean hasNext() { - return setIterator.hasNext(); - } - - public V next() { - return setIterator.next().getValue(); - } - - public void remove() { - setIterator.remove(); - } - }; - } - }; - } - return valuesCollection; - } - - @SuppressWarnings("unchecked") - @Override - protected Object clone() throws CloneNotSupportedException { - NativeScriptAbstractMap result = (NativeScriptAbstractMap) super.clone(); - result.keySet = null; - result.valuesCollection = null; - return result; - } -} diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptHashMap.java b/platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptHashMap.java deleted file mode 100644 index 488eda93..00000000 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptHashMap.java +++ /dev/null @@ -1,1056 +0,0 @@ -package com.tns; - -import java.util.AbstractCollection; -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.Arrays; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -import java.io.IOException; -import java.io.InvalidObjectException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamField; -import java.io.Serializable; - -//import libcore.util.Objects; - -/** - * HashMap is an implementation of {@link Map}. All optional operations are - * supported. - * - *

- * All elements are permitted as keys or values, including null. - * - *

- * Note that the iteration order for HashMap is non-deterministic. If you want deterministic iteration, use {@link LinkedHashMap}. - * - *

- * Note: the implementation of {@code HashMap} is not synchronized. If one thread of several threads accessing an instance modifies the map structurally, access to the map needs to be synchronized. A structural modification is an operation that adds or removes an entry. Changes in the value of an entry are not structural changes. - * - *

- * The {@code Iterator} created by calling the {@code iterator} method may throw a {@code ConcurrentModificationException} if the map is structurally changed while an iterator is used to iterate over the elements. Only the {@code remove} method that is provided by the iterator allows for removal of elements during iteration. It is not possible to guarantee that this mechanism works in all cases of unsynchronized concurrent modification. It should only be used for debugging purposes. - * - * @param the type of keys maintained by this map - * @param the type of mapped values - */ - -public class NativeScriptHashMap extends AbstractMap implements Cloneable, Serializable { - /** - * Min capacity (other than zero) for a HashMap. Must be a power of two - * greater than 1 (and less than 1 << 30). - */ - private static final int MINIMUM_CAPACITY = 4; - - /** - * Max capacity for a HashMap. Must be a power of two >= MINIMUM_CAPACITY. - */ - private static final int MAXIMUM_CAPACITY = 1 << 30; - - /** - * An empty table shared by all zero-capacity maps (typically from default - * constructor). It is never written to, and replaced on first put. Its size - * is set to half the minimum, so that the first resize will create a - * minimum-sized table. - */ - @SuppressWarnings("rawtypes") - private static final Entry[] EMPTY_TABLE = new HashMapEntry[MINIMUM_CAPACITY >>> 1]; - - /** - * The default load factor. Note that this implementation ignores the load - * factor, but cannot do away with it entirely because it's mentioned in the - * API. - * - *

- * Note that this constant has no impact on the behavior of the program, but it is emitted as part of the serialized form. The load factor of .75 is hardwired into the program, which uses cheap shifts in place of expensive division. - */ - static final float DEFAULT_LOAD_FACTOR = .75F; - - /** - * The hash table. If this hash map contains a mapping for null, it is not - * represented this hash table. - */ - transient HashMapEntry[] table; - - /** - * The entry representing the null key, or null if there's no such mapping. - */ - transient HashMapEntry entryForNullKey; - - /** - * The number of mappings in this hash map. - */ - transient int size; - - /** - * Incremented by "structural modifications" to allow (best effort) - * detection of concurrent modification. - */ - transient int modCount; - - /** - * The table is rehashed when its size exceeds this threshold. The value of - * this field is generally .75 * capacity, except when the capacity is zero, - * as described in the EMPTY_TABLE declaration above. - */ - private transient int threshold; - - // Views - lazily initialized - private transient Set keySet; - private transient Set> entrySet; - private transient Collection values; - - /** - * Constructs a new empty {@code HashMap} instance. - */ - @SuppressWarnings("unchecked") - public NativeScriptHashMap() { - table = (HashMapEntry[]) EMPTY_TABLE; - threshold = -1; // Forces first put invocation to replace EMPTY_TABLE - } - - /** - * Constructs a new {@code HashMap} instance with the specified capacity. - * - * @param capacity the initial capacity of this hash map. - * @throws IllegalArgumentException when the capacity is less than zero. - */ - public NativeScriptHashMap(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException("Capacity: " + capacity); - } - - if (capacity == 0) { - @SuppressWarnings("unchecked") - HashMapEntry[] tab = (HashMapEntry[]) EMPTY_TABLE; - table = tab; - threshold = -1; // Forces first put() to replace EMPTY_TABLE - return; - } - - if (capacity < MINIMUM_CAPACITY) { - capacity = MINIMUM_CAPACITY; - } else if (capacity > MAXIMUM_CAPACITY) { - capacity = MAXIMUM_CAPACITY; - } else { - capacity = roundUpToPowerOfTwo(capacity); - } - makeTable(capacity); - } - - /** - * Constructs a new {@code HashMap} instance with the specified capacity and - * load factor. - * - * @param capacity the initial capacity of this hash map. - * @param loadFactor the initial load factor. - * @throws IllegalArgumentException when the capacity is less than zero or the load factor is - * less or equal to zero or NaN. - */ - public NativeScriptHashMap(int capacity, float loadFactor) { - this(capacity); - - if (loadFactor <= 0 || Float.isNaN(loadFactor)) { - throw new IllegalArgumentException("Load factor: " + loadFactor); - } - - /* - * Note that this implementation ignores loadFactor; it always uses a - * load factor of 3/4. This simplifies the code and generally improves - * performance. - */ - } - - /** - * Constructs a new {@code HashMap} instance containing the mappings from - * the specified map. - * - * @param map the mappings to add. - */ - public NativeScriptHashMap(Map map) { - this(capacityForInitSize(map.size())); - constructorPutAll(map); - } - - /** - * Inserts all of the elements of map into this HashMap in a manner suitable - * for use by constructors and pseudo-constructors (i.e., clone, - * readObject). Also used by LinkedHashMap. - */ - final void constructorPutAll(Map map) { - if (table == EMPTY_TABLE) { - doubleCapacity(); // Don't do unchecked puts to a shared table. - } - for (Entry e : map.entrySet()) { - constructorPut(e.getKey(), e.getValue()); - } - } - - /** - * Returns an appropriate capacity for the specified initial size. Does not - * round the result up to a power of two; the caller must do this! The - * returned value will be between 0 and MAXIMUM_CAPACITY (inclusive). - */ - static int capacityForInitSize(int size) { - int result = (size >> 1) + size; // Multiply by 3/2 to allow for growth - - // boolean expr is equivalent to result >= 0 && result result; - try { - result = (NativeScriptHashMap) super.clone(); - } catch (CloneNotSupportedException e) { - throw new AssertionError(e); - } - - // Restore clone to empty state, retaining our capacity and threshold - result.makeTable(table.length); - result.entryForNullKey = null; - result.size = 0; - result.keySet = null; - result.entrySet = null; - result.values = null; - - result.init(); // Give subclass a chance to initialize itself - result.constructorPutAll(this); // Calls method overridden in subclass!! - return result; - } - - /** - * This method is called from the pseudo-constructors (clone and readObject) - * prior to invoking constructorPut/constructorPutAll, which invoke the - * overridden constructorNewEntry method. Normally it is a VERY bad idea to - * invoke an overridden method from a pseudo-constructor (Effective Java - * Item 17). In this case it is unavoidable, and the init method provides a - * workaround. - */ - void init() { - } - - /** - * Returns whether this map is empty. - * - * @return {@code true} if this map has no elements, {@code false} otherwise. - * @see #size() - */ - @Override - public boolean isEmpty() { - return size == 0; - } - - /** - * Returns the number of elements in this map. - * - * @return the number of elements in this map. - */ - @Override - public int size() { - return size; - } - - /** - * Returns the value of the mapping with the specified key. - * - * @param key the key. - * @return the value of the mapping with the specified key, or {@code null} if no mapping for the specified key is found. - */ - public V get(Object key) { - if (key == null) { - HashMapEntry e = entryForNullKey; - return e == null ? null : e.value; - } - - int hash = secondaryHashForObject(key); - HashMapEntry[] tab = table; - for (HashMapEntry e = tab[hash & (tab.length - 1)]; e != null; e = e.next) { - K eKey = e.key; - if (eKey == key) { - return e.value; - } - } - return null; - } - - /** - * Returns whether this map contains the specified key. - * - * @param key the key to search for. - * @return {@code true} if this map contains the specified key, {@code false} otherwise. - */ - @Override - public boolean containsKey(Object key) { - if (key == null) { - return entryForNullKey != null; - } - - int hash = secondaryHashForObject(key); - HashMapEntry[] tab = table; - for (HashMapEntry e = tab[hash & (tab.length - 1)]; e != null; e = e.next) { - K eKey = e.key; - if (eKey == key) { - return true; - } - } - return false; - } - - /** - * Returns whether this map contains the specified value. - * - * @param value the value to search for. - * @return {@code true} if this map contains the specified value, {@code false} otherwise. - */ - @Override - public boolean containsValue(Object value) { - HashMapEntry[] tab = table; - int len = tab.length; - if (value == null) { - for (int i = 0; i < len; i++) { - for (HashMapEntry e = tab[i]; e != null; e = e.next) { - if (e.value == null) { - return true; - } - } - } - return entryForNullKey != null && entryForNullKey.value == null; - } - - // value is non-null - for (int i = 0; i < len; i++) { - for (HashMapEntry e = tab[i]; e != null; e = e.next) { - if (value == e.value) { - return true; - } - } - } - return entryForNullKey != null && value.equals(entryForNullKey.value); - } - - /** - * Maps the specified key to the specified value. - * - * @param key the key. - * @param value the value. - * @return the value of any previous mapping with the specified key or {@code null} if there was no such mapping. - */ - @Override - public V put(K key, V value) { - if (key == null) { - return putValueForNullKey(value); - } - - int hash = secondaryHashForObject(key); - HashMapEntry[] tab = table; - int index = hash & (tab.length - 1); - for (HashMapEntry e = tab[index]; e != null; e = e.next) { - K eKey = e.key; - if (eKey == key) { - preModify(e); - V oldValue = e.value; - e.value = value; - return oldValue; - } - } - - // No entry for (non-null) key is present; create one - modCount++; - if (size++ > threshold) { - tab = doubleCapacity(); - index = hash & (tab.length - 1); - } - addNewEntry(key, value, hash, index); - return null; - } - - private V putValueForNullKey(V value) { - HashMapEntry entry = entryForNullKey; - if (entry == null) { - addNewEntryForNullKey(value); - size++; - modCount++; - return null; - } else { - preModify(entry); - V oldValue = entry.value; - entry.value = value; - return oldValue; - } - } - - /** - * Give LinkedHashMap a chance to take action when we modify an existing - * entry. - * - * @param e the entry we're about to modify. - */ - void preModify(HashMapEntry e) { - } - - /** - * This method is just like put, except that it doesn't do things that are - * inappropriate or unnecessary for constructors and pseudo-constructors - * (i.e., clone, readObject). In particular, this method does not check to - * ensure that capacity is sufficient, and does not increment modCount. - */ - private void constructorPut(K key, V value) { - if (key == null) { - HashMapEntry entry = entryForNullKey; - if (entry == null) { - entryForNullKey = constructorNewEntry(null, value, 0, null); - size++; - } else { - entry.value = value; - } - return; - } - - int hash = secondaryHashForObject(key); - HashMapEntry[] tab = table; - int index = hash & (tab.length - 1); - HashMapEntry first = tab[index]; - for (HashMapEntry e = first; e != null; e = e.next) { - if (key == e.key) { - e.value = value; - return; - } - } - - // No entry for (non-null) key is present; create one - tab[index] = constructorNewEntry(key, value, hash, first); - size++; - } - - /** - * Creates a new entry for the given key, value, hash, and index and inserts - * it into the hash table. This method is called by put (and indirectly, - * putAll), and overridden by LinkedHashMap. The hash must incorporate the - * secondary hash function. - */ - void addNewEntry(K key, V value, int hash, int index) { - table[index] = new HashMapEntry(key, value, hash, table[index]); - } - - /** - * Creates a new entry for the null key, and the given value and inserts it - * into the hash table. This method is called by put (and indirectly, - * putAll), and overridden by LinkedHashMap. - */ - void addNewEntryForNullKey(V value) { - entryForNullKey = new HashMapEntry(null, value, 0, null); - } - - /** - * Like newEntry, but does not perform any activity that would be - * unnecessary or inappropriate for constructors. In this class, the two - * methods behave identically; in LinkedHashMap, they differ. - */ - HashMapEntry constructorNewEntry(K key, V value, int hash, HashMapEntry first) { - return new HashMapEntry(key, value, hash, first); - } - - /** - * Copies all the mappings in the specified map to this map. These mappings - * will replace all mappings that this map had for any of the keys currently - * in the given map. - * - * @param map the map to copy mappings from. - */ - @Override - public void putAll(Map map) { - ensureCapacity(map.size()); - super.putAll(map); - } - - /** - * Ensures that the hash table has sufficient capacity to store the - * specified number of mappings, with room to grow. If not, it increases the - * capacity as appropriate. Like doubleCapacity, this method moves existing - * entries to new buckets as appropriate. Unlike doubleCapacity, this method - * can grow the table by factors of 2^n for n > 1. Hopefully, a single call - * to this method will be faster than multiple calls to doubleCapacity. - * - *

- * This method is called only by putAll. - */ - private void ensureCapacity(int numMappings) { - int newCapacity = roundUpToPowerOfTwo(capacityForInitSize(numMappings)); - HashMapEntry[] oldTable = table; - int oldCapacity = oldTable.length; - if (newCapacity <= oldCapacity) { - return; - } - if (newCapacity == oldCapacity * 2) { - doubleCapacity(); - return; - } - - // We're growing by at least 4x, rehash in the obvious way - HashMapEntry[] newTable = makeTable(newCapacity); - if (size != 0) { - int newMask = newCapacity - 1; - for (int i = 0; i < oldCapacity; i++) { - for (HashMapEntry e = oldTable[i]; e != null; ) { - HashMapEntry oldNext = e.next; - int newIndex = e.hash & newMask; - HashMapEntry newNext = newTable[newIndex]; - newTable[newIndex] = e; - e.next = newNext; - e = oldNext; - } - } - } - } - - /** - * Allocate a table of the given capacity and set the threshold accordingly. - * - * @param newCapacity must be a power of two - */ - private HashMapEntry[] makeTable(int newCapacity) { - @SuppressWarnings({"unchecked", "rawtypes"}) - HashMapEntry[] newTable = (HashMapEntry[]) new HashMapEntry[newCapacity]; - table = newTable; - threshold = (newCapacity >> 1) + (newCapacity >> 2); // 3/4 capacity - return newTable; - } - - /** - * Doubles the capacity of the hash table. Existing entries are placed in - * the correct bucket on the enlarged table. If the current capacity is, - * MAXIMUM_CAPACITY, this method is a no-op. Returns the table, which will - * be new unless we were already at MAXIMUM_CAPACITY. - */ - private HashMapEntry[] doubleCapacity() { - HashMapEntry[] oldTable = table; - int oldCapacity = oldTable.length; - if (oldCapacity == MAXIMUM_CAPACITY) { - return oldTable; - } - int newCapacity = oldCapacity * 2; - HashMapEntry[] newTable = makeTable(newCapacity); - if (size == 0) { - return newTable; - } - - for (int j = 0; j < oldCapacity; j++) { - /* - * Rehash the bucket using the minimum number of field writes. This - * is the most subtle and delicate code in the class. - */ - HashMapEntry e = oldTable[j]; - if (e == null) { - continue; - } - int highBit = e.hash & oldCapacity; - HashMapEntry broken = null; - newTable[j | highBit] = e; - for (HashMapEntry n = e.next; n != null; e = n, n = n.next) { - int nextHighBit = n.hash & oldCapacity; - if (nextHighBit != highBit) { - if (broken == null) { - newTable[j | nextHighBit] = n; - } else { - broken.next = n; - } - broken = e; - highBit = nextHighBit; - } - } - if (broken != null) { - broken.next = null; - } - } - return newTable; - } - - /** - * Removes the mapping with the specified key from this map. - * - * @param key the key of the mapping to remove. - * @return the value of the removed mapping or {@code null} if no mapping - * for the specified key was found. - */ - @Override - public V remove(Object key) { - if (key == null) { - return removeNullKey(); - } - int hash = secondaryHashForObject(key); - HashMapEntry[] tab = table; - int index = hash & (tab.length - 1); - for (HashMapEntry e = tab[index], prev = null; e != null; prev = e, e = e.next) { - K eKey = e.key; - if (eKey == key) { - if (prev == null) { - tab[index] = e.next; - } else { - prev.next = e.next; - } - modCount++; - size--; - postRemove(e); - return e.value; - } - } - return null; - } - - private V removeNullKey() { - HashMapEntry e = entryForNullKey; - if (e == null) { - return null; - } - entryForNullKey = null; - modCount++; - size--; - postRemove(e); - return e.value; - } - - /** - * Subclass overrides this method to unlink entry. - */ - void postRemove(HashMapEntry e) { - } - - /** - * Removes all mappings from this hash map, leaving it empty. - * - * @see #isEmpty - * @see #size - */ - @Override - public void clear() { - if (size != 0) { - Arrays.fill(table, null); - entryForNullKey = null; - modCount++; - size = 0; - } - } - - /** - * Returns a set of the keys contained in this map. The set is backed by - * this map so changes to one are reflected by the other. The set does not - * support adding. - * - * @return a set of the keys. - */ - @Override - public Set keySet() { - Set ks = keySet; - return (ks != null) ? ks : (keySet = new KeySet()); - } - - /** - * Returns a collection of the values contained in this map. The collection - * is backed by this map so changes to one are reflected by the other. The - * collection supports remove, removeAll, retainAll and clear operations, - * and it does not support add or addAll operations. - *

- * This method returns a collection which is the subclass of AbstractCollection. The iterator method of this subclass returns a "wrapper object" over the iterator of map's entrySet(). The {@code size} method wraps the map's size method and the {@code contains} method wraps the map's containsValue method. - *

- *

- * The collection is created when this method is called for the first time and returned in response to all subsequent calls. This method may return different collections when multiple concurrent calls occur, since no synchronization is performed. - *

- * - * @return a collection of the values contained in this map. - */ - @Override - public Collection values() { - Collection vs = values; - return (vs != null) ? vs : (values = new Values()); - } - - /** - * Returns a set containing all of the mappings in this map. Each mapping is - * an instance of {@link Map.Entry}. As the set is backed by this map, - * changes in one will be reflected in the other. - * - * @return a set of the mappings. - */ - public Set> entrySet() { - Set> es = entrySet; - return (es != null) ? es : (entrySet = new EntrySet()); - } - - static class HashMapEntry implements Entry { - final K key; - V value; - final int hash; - HashMapEntry next; - - HashMapEntry(K key, V value, int hash, HashMapEntry next) { - this.key = key; - this.value = value; - this.hash = hash; - this.next = next; - } - - public final K getKey() { - return key; - } - - public final V getValue() { - return value; - } - - public final V setValue(V value) { - V oldValue = this.value; - this.value = value; - return oldValue; - } - - @Override - public final boolean equals(Object o) { - if (!(o instanceof Entry)) { - return false; - } - Entry e = (Entry) o; - return key == e.getKey() && value == e.getValue(); - } - - @Override - public final int hashCode() { - return hash ^ (value == null ? 0 : value.hashCode()); - } - - @Override - public final String toString() { - return key + "=" + value; - } - } - - private abstract class HashIterator { - int nextIndex; - HashMapEntry nextEntry = entryForNullKey; - HashMapEntry lastEntryReturned; - int expectedModCount = modCount; - - HashIterator() { - if (nextEntry == null) { - HashMapEntry[] tab = table; - HashMapEntry next = null; - while (next == null && nextIndex < tab.length) { - next = tab[nextIndex++]; - } - nextEntry = next; - } - } - - public boolean hasNext() { - return nextEntry != null; - } - - HashMapEntry nextEntry() { - if (modCount != expectedModCount) { - throw new ConcurrentModificationException(); - } - if (nextEntry == null) { - throw new NoSuchElementException(); - } - - HashMapEntry entryToReturn = nextEntry; - HashMapEntry[] tab = table; - HashMapEntry next = entryToReturn.next; - while (next == null && nextIndex < tab.length) { - next = tab[nextIndex++]; - } - nextEntry = next; - return lastEntryReturned = entryToReturn; - } - - public void remove() { - if (lastEntryReturned == null) { - throw new IllegalStateException(); - } - if (modCount != expectedModCount) { - throw new ConcurrentModificationException(); - } - NativeScriptHashMap.this.remove(lastEntryReturned.key); - lastEntryReturned = null; - expectedModCount = modCount; - } - } - - private final class KeyIterator extends HashIterator implements Iterator { - public K next() { - return nextEntry().key; - } - } - - private final class ValueIterator extends HashIterator implements Iterator { - public V next() { - return nextEntry().value; - } - } - - private final class EntryIterator extends HashIterator implements Iterator> { - public Entry next() { - return nextEntry(); - } - } - - /** - * Returns true if this map contains the specified mapping. - */ - private boolean containsMapping(Object key, Object value) { - if (key == null) { - HashMapEntry e = entryForNullKey; - return e != null && Objects.equal(value, e.value); - } - - int hash = secondaryHashForObject(key); - HashMapEntry[] tab = table; - int index = hash & (tab.length - 1); - for (HashMapEntry e = tab[index]; e != null; e = e.next) { - if (key == e.key) { - return Objects.equal(value, e.value); - } - } - return false; // No entry for key - } - - /** - * Removes the mapping from key to value and returns true if this mapping - * exists; otherwise, returns does nothing and returns false. - */ - private boolean removeMapping(Object key, Object value) { - if (key == null) { - HashMapEntry e = entryForNullKey; - if (e == null || !Objects.equal(value, e.value)) { - return false; - } - entryForNullKey = null; - modCount++; - size--; - postRemove(e); - return true; - } - - int hash = secondaryHashForObject(key); - HashMapEntry[] tab = table; - int index = hash & (tab.length - 1); - for (HashMapEntry e = tab[index], prev = null; e != null; prev = e, e = e.next) { - if (key == e.key) { - if (!Objects.equal(value, e.value)) { - return false; // Map has wrong value for key - } - if (prev == null) { - tab[index] = e.next; - } else { - prev.next = e.next; - } - modCount++; - size--; - postRemove(e); - return true; - } - } - return false; // No entry for key - } - - // Subclass (LinkedHashMap) overrides these for correct iteration order - Iterator newKeyIterator() { - return new KeyIterator(); - } - - Iterator newValueIterator() { - return new ValueIterator(); - } - - Iterator> newEntryIterator() { - return new EntryIterator(); - } - - private final class KeySet extends AbstractSet { - public Iterator iterator() { - return newKeyIterator(); - } - - public int size() { - return size; - } - - public boolean isEmpty() { - return size == 0; - } - - public boolean contains(Object o) { - return containsKey(o); - } - - public boolean remove(Object o) { - int oldSize = size; - NativeScriptHashMap.this.remove(o); - return size != oldSize; - } - - public void clear() { - NativeScriptHashMap.this.clear(); - } - } - - private final class Values extends AbstractCollection { - public Iterator iterator() { - return newValueIterator(); - } - - public int size() { - return size; - } - - public boolean isEmpty() { - return size == 0; - } - - public boolean contains(Object o) { - return containsValue(o); - } - - public void clear() { - NativeScriptHashMap.this.clear(); - } - } - - private final class EntrySet extends AbstractSet> { - public Iterator> iterator() { - return newEntryIterator(); - } - - public boolean contains(Object o) { - if (!(o instanceof Entry)) { - return false; - } - Entry e = (Entry) o; - return containsMapping(e.getKey(), e.getValue()); - } - - public boolean remove(Object o) { - if (!(o instanceof Entry)) { - return false; - } - Entry e = (Entry) o; - return removeMapping(e.getKey(), e.getValue()); - } - - public int size() { - return size; - } - - public boolean isEmpty() { - return size == 0; - } - - public void clear() { - NativeScriptHashMap.this.clear(); - } - } - - private static final long serialVersionUID = 362498820763181265L; - - private static final ObjectStreamField[] serialPersistentFields = - {new ObjectStreamField("loadFactor", float.class)}; - - private void writeObject(ObjectOutputStream stream) throws IOException { - // Emulate loadFactor field for other implementations to read - ObjectOutputStream.PutField fields = stream.putFields(); - fields.put("loadFactor", DEFAULT_LOAD_FACTOR); - stream.writeFields(); - - stream.writeInt(table.length); // Capacity - stream.writeInt(size); - for (Entry e : entrySet()) { - stream.writeObject(e.getKey()); - stream.writeObject(e.getValue()); - } - } - - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - int capacity = stream.readInt(); - if (capacity < 0) { - throw new InvalidObjectException("Capacity: " + capacity); - } - if (capacity < MINIMUM_CAPACITY) { - capacity = MINIMUM_CAPACITY; - } else if (capacity > MAXIMUM_CAPACITY) { - capacity = MAXIMUM_CAPACITY; - } else { - capacity = roundUpToPowerOfTwo(capacity); - } - makeTable(capacity); - - int size = stream.readInt(); - if (size < 0) { - throw new InvalidObjectException("Size: " + size); - } - - init(); // Give subclass (LinkedHashMap) a chance to initialize itself - for (int i = 0; i < size; i++) { - @SuppressWarnings("unchecked") - K key = (K) stream.readObject(); - @SuppressWarnings("unchecked") - V val = (V) stream.readObject(); - constructorPut(key, val); - } - } - - // ~~~~~~~~~~~~~~ - - private static int roundUpToPowerOfTwo(int i) { - i--; // If input is a power of two, shift its high-order bit right. - - // "Smear" the high-order bit all the way to the right. - i |= i >>> 1; - i |= i >>> 2; - i |= i >>> 4; - i |= i >>> 8; - i |= i >>> 16; - - return i + 1; - } - - private static int secondaryHashForObject(Object key) { - int intHash; - - if (key instanceof NativeScriptHashCodeProvider) { - NativeScriptHashCodeProvider provider = (NativeScriptHashCodeProvider) key; - intHash = provider.hashCode__super(); - } else { - intHash = System.identityHashCode(key); - } - - return secondaryHashForInt(intHash); - } - - private static int secondaryHashForInt(int h) { - // Spread bits to regularize both segment and index locations, - // using variant of single-word Wang/Jenkins hash. - h += (h << 15) ^ 0xffffcd7d; - h ^= (h >>> 10); - h += (h << 3); - h ^= (h >>> 6); - h += (h << 2) + (h << 14); - return h ^ (h >>> 16); - } -} \ No newline at end of file diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptWeakHashMap.java b/platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptWeakHashMap.java deleted file mode 100644 index b66d00fe..00000000 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/NativeScriptWeakHashMap.java +++ /dev/null @@ -1,725 +0,0 @@ -package com.tns; - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.lang.ref.ReferenceQueue; -import java.lang.ref.WeakReference; -import java.util.AbstractCollection; -import java.util.AbstractSet; -import java.util.Arrays; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -/** - * WeakHashMap is an implementation of Map with keys which are WeakReferences. A - * key/value mapping is removed when the key is no longer referenced. All - * optional operations (adding and removing) are supported. Keys and values can - * be any objects. Note that the garbage collector acts similar to a second - * thread on this collection, possibly removing keys. - * - * @since 1.2 - * @see HashMap - * @see WeakReference - */ -public class NativeScriptWeakHashMap extends NativeScriptAbstractMap implements Map { - - private static final int DEFAULT_SIZE = 16; - - private final ReferenceQueue referenceQueue; - - int elementCount; - - Entry[] elementData; - - private final int loadFactor; - - private int threshold; - - volatile int modCount; - - // Simple utility method to isolate unchecked cast for array creation - @SuppressWarnings({"unchecked", "rawtypes"}) - private static Entry[] newEntryArray(int size) { - return new Entry[size]; - } - - private static final class Entry extends WeakReference implements Map.Entry { - final int hash; - - boolean isNull; - - V value; - - Entry next; - - interface Type { - RET get(Map.Entry entry); - } - - Entry(K key, V object, ReferenceQueue queue) { - super(key, queue); - isNull = key == null; - hash = isNull ? 0 : secondaryHashForObject(key); - value = object; - } - - public K getKey() { - return super.get(); - } - - public V getValue() { - return value; - } - - public V setValue(V object) { - V result = value; - value = object; - return result; - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof Map.Entry)) { - return false; - } - Map.Entry entry = (Map.Entry) other; - Object key = super.get(); - return (key == null ? key == entry.getKey() : key == entry.getKey()) && (value == null ? value == entry.getValue() : value == entry.getValue()); - } - - @Override - public int hashCode() { - return hash + (value == null ? 0 : value.hashCode()); - } - - @Override - public String toString() { - return super.get() + "=" + value; - } - } - - class HashIterator implements Iterator { - private int position = 0, expectedModCount; - - private Entry currentEntry, nextEntry; - - private K nextKey; - - final Entry.Type type; - - HashIterator(Entry.Type type) { - this.type = type; - expectedModCount = modCount; - } - - public boolean hasNext() { - if (nextEntry != null && (nextKey != null || nextEntry.isNull)) { - return true; - } - while (true) { - if (nextEntry == null) { - while (position < elementData.length) { - if ((nextEntry = elementData[position++]) != null) { - break; - } - } - if (nextEntry == null) { - return false; - } - } - // ensure key of next entry is not gc'ed - nextKey = nextEntry.get(); - if (nextKey != null || nextEntry.isNull) { - return true; - } - nextEntry = nextEntry.next; - } - } - - public RET next() { - if (expectedModCount == modCount) { - if (hasNext()) { - currentEntry = nextEntry; - nextEntry = currentEntry.next; - RET result = type.get(currentEntry); - // free the key - nextKey = null; - return result; - } - throw new NoSuchElementException(); - } - throw new ConcurrentModificationException(); - } - - public void remove() { - if (expectedModCount == modCount) { - if (currentEntry != null) { - removeEntry(currentEntry); - currentEntry = null; - expectedModCount++; - // cannot poll() as that would change the expectedModCount - } else { - throw new IllegalStateException(); - } - } else { - throw new ConcurrentModificationException(); - } - } - } - - /** - * Constructs a new empty {@code WeakHashMap} instance. - */ - public NativeScriptWeakHashMap() { - this(DEFAULT_SIZE); - } - - /** - * Constructs a new {@code WeakHashMap} instance with the specified - * capacity. - * - * @param capacity - * the initial capacity of this map. - * @throws IllegalArgumentException - * if the capacity is less than zero. - */ - public NativeScriptWeakHashMap(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException("capacity < 0: " + capacity); - } - elementCount = 0; - elementData = newEntryArray(capacity == 0 ? 1 : capacity); - loadFactor = 7500; // Default load factor of 0.75 - computeMaxSize(); - referenceQueue = new ReferenceQueue(); - } - - /** - * Constructs a new {@code WeakHashMap} instance with the specified capacity - * and load factor. - * - * @param capacity - * the initial capacity of this map. - * @param loadFactor - * the initial load factor. - * @throws IllegalArgumentException - * if the capacity is less than zero or the load factor is less - * or equal to zero. - */ - public NativeScriptWeakHashMap(int capacity, float loadFactor) { - if (capacity < 0) { - throw new IllegalArgumentException("capacity < 0: " + capacity); - } - if (loadFactor <= 0) { - throw new IllegalArgumentException("loadFactor <= 0: " + loadFactor); - } - elementCount = 0; - elementData = newEntryArray(capacity == 0 ? 1 : capacity); - this.loadFactor = (int) (loadFactor * 10000); - computeMaxSize(); - referenceQueue = new ReferenceQueue(); - } - - /** - * Constructs a new {@code WeakHashMap} instance containing the mappings - * from the specified map. - * - * @param map - * the mappings to add. - */ - public NativeScriptWeakHashMap(Map map) { - this(map.size() < 6 ? 11 : map.size() * 2); - putAllImpl(map); - } - - /** - * Removes all mappings from this map, leaving it empty. - * - * @see #isEmpty() - * @see #size() - */ - @Override - public void clear() { - if (elementCount > 0) { - elementCount = 0; - Arrays.fill(elementData, null); - modCount++; - while (referenceQueue.poll() != null) { - // do nothing - } - } - } - - private void computeMaxSize() { - threshold = (int) ((long) elementData.length * loadFactor / 10000); - } - - /** - * Returns whether this map contains the specified key. - * - * @param key - * the key to search for. - * @return {@code true} if this map contains the specified key, {@code false} otherwise. - */ - @Override - public boolean containsKey(Object key) { - return getEntry(key) != null; - } - - /** - * Returns a set containing all of the mappings in this map. Each mapping is - * an instance of {@link Map.Entry}. As the set is backed by this map, - * changes in one will be reflected in the other. It does not support adding - * operations. - * - * @return a set of the mappings. - */ - @Override - public Set> entrySet() { - poll(); - return new AbstractSet>() { - @Override - public int size() { - return NativeScriptWeakHashMap.this.size(); - } - - @Override - public void clear() { - NativeScriptWeakHashMap.this.clear(); - } - - @Override - public boolean remove(Object object) { - if (contains(object)) { - NativeScriptWeakHashMap.this.remove(((Map.Entry) object).getKey()); - return true; - } - return false; - } - - @Override - public boolean contains(Object object) { - if (object instanceof Map.Entry) { - Entry entry = getEntry(((Map.Entry) object).getKey()); - if (entry != null) { - Object key = entry.get(); - if (key != null || entry.isNull) { - return object.equals(entry); - } - } - } - return false; - } - - @Override - public Iterator> iterator() { - return new HashIterator>(new Entry.Type, K, V>() { - public Map.Entry get(Map.Entry entry) { - return entry; - } - }); - } - }; - } - - /** - * Returns a set of the keys contained in this map. The set is backed by - * this map so changes to one are reflected by the other. The set does not - * support adding. - * - * @return a set of the keys. - */ - @Override - public Set keySet() { - poll(); - if (keySet == null) { - keySet = new AbstractSet() { - @Override - public boolean contains(Object object) { - return containsKey(object); - } - - @Override - public int size() { - return NativeScriptWeakHashMap.this.size(); - } - - @Override - public void clear() { - NativeScriptWeakHashMap.this.clear(); - } - - @Override - public boolean remove(Object key) { - if (containsKey(key)) { - NativeScriptWeakHashMap.this.remove(key); - return true; - } - return false; - } - - @Override - public Iterator iterator() { - return new HashIterator(new Entry.Type() { - public K get(Map.Entry entry) { - return entry.getKey(); - } - }); - } - }; - } - return keySet; - } - - /** - * Returns a collection of the values contained in this map. The collection - * is backed by this map so changes to one are reflected by the other. The - * collection supports remove, removeAll, retainAll and clear operations, - * and it does not support add or addAll operations. - *

- * This method returns a collection which is the subclass of AbstractCollection. The iterator method of this subclass returns a "wrapper object" over the iterator of map's entrySet(). The size method wraps the map's size method and the contains method wraps the map's containsValue method. - *

- * The collection is created when this method is called at first time and returned in response to all subsequent calls. This method may return different Collection when multiple calls to this method, since it has no synchronization performed. - * - * @return a collection of the values contained in this map. - */ - @Override - public Collection values() { - poll(); - if (valuesCollection == null) { - valuesCollection = new AbstractCollection() { - @Override - public int size() { - return NativeScriptWeakHashMap.this.size(); - } - - @Override - public void clear() { - NativeScriptWeakHashMap.this.clear(); - } - - @Override - public boolean contains(Object object) { - return containsValue(object); - } - - @Override - public Iterator iterator() { - return new HashIterator(new Entry.Type() { - public V get(Map.Entry entry) { - return entry.getValue(); - } - }); - } - }; - } - return valuesCollection; - } - - /** - * Returns the value of the mapping with the specified key. - * - * @param key - * the key. - * @return the value of the mapping with the specified key, or {@code null} if no mapping for the specified key is found. - */ - @Override - public V get(Object key) { - poll(); - if (key != null) { - int index = (secondaryHashForObject(key) & 0x7FFFFFFF) % elementData.length; - Entry entry = elementData[index]; - while (entry != null) { - if (key == entry.get()) { - return entry.value; - } - entry = entry.next; - } - return null; - } - Entry entry = elementData[0]; - while (entry != null) { - if (entry.isNull) { - return entry.value; - } - entry = entry.next; - } - return null; - } - - Entry getEntry(Object key) { - poll(); - if (key != null) { - int index = (secondaryHashForObject(key) & 0x7FFFFFFF) % elementData.length; - Entry entry = elementData[index]; - while (entry != null) { - if (key == entry.get()) { - return entry; - } - entry = entry.next; - } - return null; - } - Entry entry = elementData[0]; - while (entry != null) { - if (entry.isNull) { - return entry; - } - entry = entry.next; - } - return null; - } - - /** - * Returns whether this map contains the specified value. - * - * @param value - * the value to search for. - * @return {@code true} if this map contains the specified value, {@code false} otherwise. - */ - @Override - public boolean containsValue(Object value) { - poll(); - if (value != null) { - for (int i = elementData.length; --i >= 0;) { - Entry entry = elementData[i]; - while (entry != null) { - K key = entry.get(); - if ((key != null || entry.isNull) && value == entry.value) { - return true; - } - entry = entry.next; - } - } - } else { - for (int i = elementData.length; --i >= 0;) { - Entry entry = elementData[i]; - while (entry != null) { - K key = entry.get(); - if ((key != null || entry.isNull) && entry.value == null) { - return true; - } - entry = entry.next; - } - } - } - return false; - } - - /** - * Returns the number of elements in this map. - * - * @return the number of elements in this map. - */ - @Override - public boolean isEmpty() { - return size() == 0; - } - - @SuppressWarnings("unchecked") - void poll() { - Entry toRemove; - while ((toRemove = (Entry) referenceQueue.poll()) != null) { - removeEntry(toRemove); - } - } - - void removeEntry(Entry toRemove) { - Entry entry, last = null; - int index = (toRemove.hash & 0x7FFFFFFF) % elementData.length; - entry = elementData[index]; - // Ignore queued entries which cannot be found, the user could - // have removed them before they were queued, i.e. using clear() - while (entry != null) { - if (toRemove == entry) { - modCount++; - if (last == null) { - elementData[index] = entry.next; - } else { - last.next = entry.next; - } - elementCount--; - break; - } - last = entry; - entry = entry.next; - } - } - - /** - * Maps the specified key to the specified value. - * - * @param key - * the key. - * @param value - * the value. - * @return the value of any previous mapping with the specified key or {@code null} if there was no mapping. - */ - @Override - public V put(K key, V value) { - poll(); - int index = 0; - Entry entry; - if (key != null) { - index = (secondaryHashForObject(key) & 0x7FFFFFFF) % elementData.length; - entry = elementData[index]; - while (entry != null && key != entry.get()) { - entry = entry.next; - } - } else { - entry = elementData[0]; - while (entry != null && !entry.isNull) { - entry = entry.next; - } - } - if (entry == null) { - modCount++; - if (++elementCount > threshold) { - rehash(); - index = key == null ? 0 : (secondaryHashForObject(key) & 0x7FFFFFFF) % elementData.length; - } - entry = new Entry(key, value, referenceQueue); - entry.next = elementData[index]; - elementData[index] = entry; - return null; - } - V result = entry.value; - entry.value = value; - return result; - } - - private void rehash() { - int length = elementData.length * 2; - if (length == 0) { - length = 1; - } - Entry[] newData = newEntryArray(length); - for (int i = 0; i < elementData.length; i++) { - Entry entry = elementData[i]; - while (entry != null) { - int index = entry.isNull ? 0 : (entry.hash & 0x7FFFFFFF) % length; - Entry next = entry.next; - entry.next = newData[index]; - newData[index] = entry; - entry = next; - } - } - elementData = newData; - computeMaxSize(); - } - - /** - * Copies all the mappings in the given map to this map. These mappings will - * replace all mappings that this map had for any of the keys currently in - * the given map. - * - * @param map - * the map to copy mappings from. - * @throws NullPointerException - * if {@code map} is {@code null}. - */ - @Override - public void putAll(Map map) { - putAllImpl(map); - } - - /** - * Removes the mapping with the specified key from this map. - * - * @param key - * the key of the mapping to remove. - * @return the value of the removed mapping or {@code null} if no mapping - * for the specified key was found. - */ - @Override - public V remove(Object key) { - poll(); - int index = 0; - Entry entry, last = null; - if (key != null) { - index = (secondaryHashForObject(key) & 0x7FFFFFFF) % elementData.length; - entry = elementData[index]; - while (entry != null && key != entry.get()) { - last = entry; - entry = entry.next; - } - } else { - entry = elementData[0]; - while (entry != null && !entry.isNull) { - last = entry; - entry = entry.next; - } - } - if (entry != null) { - modCount++; - if (last == null) { - elementData[index] = entry.next; - } else { - last.next = entry.next; - } - elementCount--; - return entry.value; - } - return null; - } - - /** - * Returns the number of elements in this map. - * - * @return the number of elements in this map. - */ - @Override - public int size() { - poll(); - return elementCount; - } - - private void putAllImpl(Map map) { - if (map.entrySet() != null) { - super.putAll(map); - } - } - - private static int secondaryHashForObject(Object key) { - int intHash; - - if (key instanceof NativeScriptHashCodeProvider) { - NativeScriptHashCodeProvider provider = (NativeScriptHashCodeProvider) key; - intHash = provider.hashCode__super(); - } else { - intHash = System.identityHashCode(key); - } - - return secondaryHashForInt(intHash); - } - - private static int secondaryHashForInt(int h) { - // Spread bits to regularize both segment and index locations, - // using variant of single-word Wang/Jenkins hash. - h += (h << 15) ^ 0xffffcd7d; - h ^= (h >>> 10); - h += (h << 3); - h ^= (h >>> 6); - h += (h << 2) + (h << 14); - return h ^ (h >>> 16); - } -} diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/ObjectTable.java b/platforms/android/test-app/runtime/src/main/java/com/tns/ObjectTable.java new file mode 100644 index 00000000..3d815639 --- /dev/null +++ b/platforms/android/test-app/runtime/src/main/java/com/tns/ObjectTable.java @@ -0,0 +1,481 @@ +package com.tns; + +import java.lang.ref.WeakReference; + +final class ObjectTable { + static final int NO_ID = -1; + + static final long FRESH = 1L << 32; + + interface IdSource { + int newId(); + } + + private final Stamps stamps; + + ObjectTable() { + this(false); + } + + ObjectTable(boolean optimisticReads) { + stamps = optimisticReads ? new Stamps() : null; + } + + private static final class Stamps { + private final java.util.concurrent.locks.StampedLock lock = new java.util.concurrent.locks.StampedLock(); + + long beginWrite() { + return lock.writeLock(); + } + + void endWrite(long stamp) { + lock.unlockWrite(stamp); + } + + long beginRead() { + return lock.tryOptimisticRead(); + } + + long readLock() { + return lock.readLock(); + } + + void unlockRead(long stamp) { + lock.unlockRead(stamp); + } + + boolean validate(long stamp) { + return lock.validate(stamp); + } + } + + private int findIdUnlocked(Object obj) { + int[] index = identityIndex; + int[] hashes = identityIndexHashes; + int mask = index.length - 1; + int hash = System.identityHashCode(obj); + int i = mix(hash) & mask; + for (int probes = 0; probes <= mask; probes++) { + int entry = index[i]; + if (entry == 0) { + return NO_ID; + } + if (hashes[i] == hash && getUnlocked(entry - 1) == obj) { + return entry - 1; + } + i = (i + 1) & mask; + } + return NO_ID; + } + + private Object getUnlocked(int id) { + if (id == NO_ID) { + return null; + } + Chunk[] cs = chunks; + int c = id >>> CHUNK_SHIFT; + if (c >= cs.length) { + return null; + } + Chunk chunk = cs[c]; + if (chunk == null) { + return null; + } + Leaf leaf = chunk.leaves[(id >>> LEAF_BITS) & CHUNK_MASK]; + if (leaf == null) { + return null; + } + Object value = leaf.values[id & LEAF_MASK]; + return value == null ? null : deref(value); + } + + private static Object deref(Object value) { + return value instanceof WeakRef ? ((WeakRef) value).get() : value; + } + + private static final int LEAF_BITS = 6; + private static final int LEAF_SIZE = 1 << LEAF_BITS; + private static final int LEAF_MASK = LEAF_SIZE - 1; + private static final int CHUNK_BITS = 6; + private static final int CHUNK_MASK = (1 << CHUNK_BITS) - 1; + private static final int CHUNK_SHIFT = LEAF_BITS + CHUNK_BITS; + + private static final class Leaf { + final Object[] values = new Object[LEAF_SIZE]; + final int[] hashes = new int[LEAF_SIZE]; + int live; + } + + private static final class Chunk { + final Leaf[] leaves = new Leaf[1 << CHUNK_BITS]; + int liveLeaves; + } + + private Chunk[] chunks = new Chunk[16]; + private int newestLeaf = 0; + private int idCount = 0; + + private int[] identityIndex = new int[1024]; + private int[] identityIndexHashes = new int[1024]; + private int identityCount = 0; + + void putStrong(int id, Object obj) { + if (stamps == null) { + putStrongLocked(id, obj); + return; + } + long stamp = stamps.beginWrite(); + try { + putStrongLocked(id, obj); + } finally { + stamps.endWrite(stamp); + } + } + + private void putStrongLocked(int id, Object obj) { + putStrongLocked(id, obj, System.identityHashCode(obj)); + } + + private void putStrongLocked(int id, Object obj, int hash) { + Leaf existingLeaf = leafFor(id); + if (existingLeaf != null) { + Object value = existingLeaf.values[id & LEAF_MASK]; + if (value != null) { + if (deref(value) == obj) { + existingLeaf.values[id & LEAF_MASK] = obj; + return; + } + removeLocked(id); + } + } + + insertEntry(id, obj, hash); + idCount++; + + if ((identityCount + 1) * 2 > identityIndex.length) { + growIdentity(); + } + insertIdentity(hash, id); + identityCount++; + } + + boolean allowsConcurrentRegistration() { + return stamps != null; + } + + long findOrRegister(Object obj, IdSource ids) { + long stamp = stamps.beginWrite(); + try { + int hash = System.identityHashCode(obj); + int id = findIdLocked(obj, hash); + if (id != NO_ID) { + return id & 0xFFFFFFFFL; + } + id = ids.newId(); + putStrongLocked(id, obj, hash); + return (id & 0xFFFFFFFFL) | FRESH; + } finally { + stamps.endWrite(stamp); + } + } + + int findId(Object obj) { + if (stamps == null) { + return findIdLocked(obj); + } + long stamp = stamps.beginRead(); + if (stamp != 0) { + try { + int id = findIdUnlocked(obj); + if (stamps.validate(stamp)) { + return id; + } + } catch (RuntimeException e) { + } + } + stamp = stamps.readLock(); + try { + return findIdLocked(obj); + } finally { + stamps.unlockRead(stamp); + } + } + + private int findIdLocked(Object obj) { + return findIdLocked(obj, System.identityHashCode(obj)); + } + + private int findIdLocked(Object obj, int hash) { + int mask = identityIndex.length - 1; + int i = mix(hash) & mask; + while (true) { + int entry = identityIndex[i]; + if (entry == 0) { + return NO_ID; + } + int id = entry - 1; + if (identityIndexHashes[i] == hash && getLocked(id) == obj) { + return id; + } + i = (i + 1) & mask; + } + } + + Object get(int id) { + if (stamps == null) { + return getLocked(id); + } + long stamp = stamps.beginRead(); + if (stamp != 0) { + try { + Object value = getUnlocked(id); + if (stamps.validate(stamp)) { + return value; + } + } catch (RuntimeException e) { + } + } + stamp = stamps.readLock(); + try { + return getLocked(id); + } finally { + stamps.unlockRead(stamp); + } + } + + private Object getLocked(int id) { + Object value = rawLocked(id); + return value == null ? null : deref(value); + } + + boolean contains(int id) { + if (stamps == null) { + return rawLocked(id) != null; + } + long stamp = stamps.readLock(); + try { + return rawLocked(id) != null; + } finally { + stamps.unlockRead(stamp); + } + } + + boolean weakenAndCheckAlive(int id) { + if (stamps == null) { + return weakenAndCheckAliveLocked(id); + } + long stamp = stamps.beginWrite(); + try { + return weakenAndCheckAliveLocked(id); + } finally { + stamps.endWrite(stamp); + } + } + + void weakenAndCheckAlive(int[] ids, int count) { + if (count == 0) { + return; + } + long stamp = stamps == null ? 0 : stamps.beginWrite(); + try { + for (int i = 0; i < count; i++) { + if (!weakenAndCheckAliveLocked(ids[i])) { + ids[i] = NO_ID; + } + } + } finally { + if (stamps != null) { + stamps.endWrite(stamp); + } + } + } + + private boolean weakenAndCheckAliveLocked(int id) { + Leaf leaf = leafFor(id); + Object value = leaf == null ? null : leaf.values[id & LEAF_MASK]; + if (value == null) { + return false; + } + if (value instanceof WeakRef) { + if (((WeakRef) value).get() != null) { + return true; + } + removeLocked(id); + return false; + } + leaf.values[id & LEAF_MASK] = new WeakRef(value); + return true; + } + + void remove(int id) { + if (stamps == null) { + removeLocked(id); + return; + } + long stamp = stamps.beginWrite(); + try { + removeLocked(id); + } finally { + stamps.endWrite(stamp); + } + } + + private void removeLocked(int id) { + Leaf leaf = leafFor(id); + int i = id & LEAF_MASK; + if (leaf == null || leaf.values[i] == null) { + return; + } + int hash = leaf.hashes[i]; + leaf.values[i] = null; + leaf.hashes[i] = 0; + leaf.live--; + int leafNumber = id >>> LEAF_BITS; + if (leafNumber != newestLeaf) { + releaseIfEmpty(leafNumber); + } + idCount--; + removeIdentity(hash, id); + identityCount--; + } + + int size() { + return idCount; + } + + private static final class WeakRef extends WeakReference { + WeakRef(Object referent) { + super(referent); + } + } + + private Leaf leafFor(int id) { + if (id == NO_ID) { + return null; + } + int c = id >>> CHUNK_SHIFT; + Chunk chunk = c < chunks.length ? chunks[c] : null; + return chunk == null ? null : chunk.leaves[(id >>> LEAF_BITS) & CHUNK_MASK]; + } + + private Object rawLocked(int id) { + Leaf leaf = leafFor(id); + return leaf == null ? null : leaf.values[id & LEAF_MASK]; + } + + private void insertEntry(int id, Object value, int hash) { + int c = id >>> CHUNK_SHIFT; + if (c >= chunks.length) { + int length = chunks.length; + while (length <= c) { + length *= 2; + } + Chunk[] grown = new Chunk[length]; + System.arraycopy(chunks, 0, grown, 0, chunks.length); + chunks = grown; + } + Chunk chunk = chunks[c]; + if (chunk == null) { + chunk = new Chunk(); + chunks[c] = chunk; + } + int l = (id >>> LEAF_BITS) & CHUNK_MASK; + Leaf leaf = chunk.leaves[l]; + if (leaf == null) { + leaf = new Leaf(); + chunk.leaves[l] = leaf; + chunk.liveLeaves++; + } + int i = id & LEAF_MASK; + leaf.values[i] = value; + leaf.hashes[i] = hash; + leaf.live++; + int leafNumber = id >>> LEAF_BITS; + if (leafNumber > newestLeaf) { + int previous = newestLeaf; + newestLeaf = leafNumber; + releaseIfEmpty(previous); + } + } + + private void releaseIfEmpty(int leafNumber) { + int c = leafNumber >>> CHUNK_BITS; + Chunk chunk = c < chunks.length ? chunks[c] : null; + if (chunk == null) { + return; + } + int l = leafNumber & CHUNK_MASK; + Leaf leaf = chunk.leaves[l]; + if (leaf == null || leaf.live != 0) { + return; + } + chunk.leaves[l] = null; + if (--chunk.liveLeaves == 0 && c != (newestLeaf >>> CHUNK_BITS)) { + chunks[c] = null; + } + } + + private void insertIdentity(int hash, int id) { + insertIdentity(identityIndex, identityIndexHashes, hash, id); + } + + private static void insertIdentity(int[] index, int[] hashes, int hash, int id) { + int mask = index.length - 1; + int i = mix(hash) & mask; + while (index[i] != 0) { + i = (i + 1) & mask; + } + hashes[i] = hash; + index[i] = id + 1; + } + + private void removeIdentity(int hash, int id) { + int mask = identityIndex.length - 1; + int i = mix(hash) & mask; + while (identityIndex[i] != id + 1) { + i = (i + 1) & mask; + } + int hole = i; + int j = i; + while (true) { + j = (j + 1) & mask; + int entry = identityIndex[j]; + if (entry == 0) { + break; + } + int home = mix(identityIndexHashes[j]) & mask; + if (!isBetween(hole, home, j)) { + identityIndex[hole] = entry; + identityIndexHashes[hole] = identityIndexHashes[j]; + hole = j; + } + } + identityIndex[hole] = 0; + identityIndexHashes[hole] = 0; + } + + private static boolean isBetween(int hole, int home, int j) { + return hole <= j ? (hole < home && home <= j) : (hole < home || home <= j); + } + + private void growIdentity() { + int[] oldIndex = identityIndex; + int[] oldHashes = identityIndexHashes; + int[] index = new int[oldIndex.length * 2]; + int[] hashes = new int[index.length]; + for (int i = 0; i < oldIndex.length; i++) { + if (oldIndex[i] != 0) { + insertIdentity(index, hashes, oldHashes[i], oldIndex[i] - 1); + } + } + identityIndexHashes = hashes; + identityIndex = index; + } + + private static int mix(int h) { + h ^= (h >>> 16); + h *= 0x85ebca6b; + h ^= (h >>> 13); + return h; + } +} diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java index f7377662..8f0ef942 100644 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -15,7 +15,6 @@ import java.io.File; import java.io.IOException; -import java.lang.ref.WeakReference; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; @@ -149,13 +148,14 @@ public static void passSuppressedExceptionToJs(Throwable ex, String methodName) "Primitive types need to be manually wrapped in their respective Object wrappers.\n" + "If you are creating an instance of an inner class, make sure to always provide reference to the outer `this` as the first argument."; - private Map strongInstances = new HashMap<>(); + private final ObjectTable objectTable; - private Map> weakInstances = new HashMap<>(); - - private Map strongJavaObjectToID = new NativeScriptHashMap(); - - private Map weakJavaObjectToID = new NativeScriptWeakHashMap(); + private final ObjectTable.IdSource objectIds = new ObjectTable.IdSource() { + @Override + public int newId() { + return generateNewObjectId(getRuntimeId()); + } + }; private Map, JavaScriptImplementation> loadedJavaScriptExtends = new HashMap, JavaScriptImplementation>(); @@ -169,7 +169,6 @@ public static void passSuppressedExceptionToJs(Throwable ex, String methodName) private final java.lang.Runtime dalvikRuntime = java.lang.Runtime.getRuntime(); - private final Object keyNotFoundObject = new Object(); private int currentObjectId = -1; private ExtractPolicy extractPolicy; @@ -232,20 +231,18 @@ public int compare(Method lhs, Method rhs) { private static final ClassStorageService classStorageService = new ClassStorageServiceImpl(ClassCacheImpl.INSTANCE, ClassLoadersCollectionImpl.INSTANCE); - public Runtime(ClassResolver classResolver, GcListener gcListener, StaticConfiguration config, DynamicConfiguration dynamicConfig, int runtimeId, int workerId, HashMap strongInstances, HashMap> weakInstances, NativeScriptHashMap strongJavaObjectToId, NativeScriptWeakHashMap weakJavaObjectToId) { + public Runtime(ClassResolver classResolver, GcListener gcListener, StaticConfiguration config, DynamicConfiguration dynamicConfig, int runtimeId, int workerId, ObjectTable objectTable) { this.classResolver = classResolver; this.gcListener = gcListener; this.config = config; this.dynamicConfig = dynamicConfig; this.runtimeId = runtimeId; this.workerId = workerId; - this.strongInstances = strongInstances; - this.weakInstances = weakInstances; - this.strongJavaObjectToID = strongJavaObjectToId; - this.weakJavaObjectToID = weakJavaObjectToId; + this.objectTable = objectTable; } public Runtime(StaticConfiguration config, DynamicConfiguration dynamicConfiguration) { + this.objectTable = new ObjectTable(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N); synchronized (Runtime.currentRuntime) { ManualInstrumentation.Frame frame = ManualInstrumentation.start("new Runtime"); try { @@ -265,13 +262,9 @@ public Runtime(StaticConfiguration config, DynamicConfiguration dynamicConfigura // if multithreadedJS, make all instance maps concurrent or synchronized: if (config.appConfig.getEnableMultithreadedJavascript()) { - this.strongInstances = new ConcurrentHashMap<>(); - this.weakInstances = new ConcurrentHashMap<>(); // loadedJavaScriptExtends can store null values (unsupported by ConcurrentHashMap), // so use a synchronized map instead. this.loadedJavaScriptExtends = Collections.synchronizedMap(new HashMap<>()); - this.strongJavaObjectToID = Collections.synchronizedMap(new NativeScriptHashMap<>()); - this.weakJavaObjectToID = Collections.synchronizedMap(new NativeScriptWeakHashMap<>()); } classResolver = new ClassResolver(classStorageService); @@ -422,17 +415,7 @@ public void ResetDateTimeConfigurationCache() { } public void releaseNativeCounterpart(int nativeObjectId) { - Object strongRef = strongInstances.get(nativeObjectId); - if (strongRef != null) { - strongInstances.remove(nativeObjectId); - strongJavaObjectToID.remove(strongRef); - } - - WeakReference weakRef = weakInstances.get(nativeObjectId); - if (weakRef != null) { - weakInstances.remove(nativeObjectId); - weakJavaObjectToID.remove(weakRef); - } + objectTable.remove(nativeObjectId); } /* @@ -784,7 +767,7 @@ public void notifyGc() { public void notifyGc(int[] objectIds) { for (int id: objectIds) { - weakInstances.remove(id); + objectTable.remove(id); } notifyGc(runtimeId, objectIds); } @@ -991,8 +974,7 @@ private void makeInstanceStrong(Object instance, int objectId) { throw new IllegalArgumentException("instance cannot be null"); } - strongInstances.put(objectId, instance); - strongJavaObjectToID.put(instance, objectId); + objectTable.putStrong(objectId, instance); Class clazz = instance.getClass(); // Only resolve the name + store the class the first time we see it; the @@ -1015,10 +997,6 @@ private void makeInstanceStrong(int objectId) { Object instance = getJavaObjectByID(objectId); if (instance == null) return; makeInstanceStrong(instance, objectId); - - weakJavaObjectToID.remove(instance); - weakInstances.remove(objectId); - } catch (Exception e) { } @@ -1033,18 +1011,11 @@ private void makeInstanceWeak(int javaObjectID, boolean keepAsWeak) { if (logger.isEnabled()) { logger.write("makeInstanceWeak instance " + javaObjectID + " keepAsWeak=" + keepAsWeak); } - Object instance = strongInstances.get(javaObjectID); - - // object is marked as weak already, - if (instance == null) return; - if (keepAsWeak) { - weakJavaObjectToID.put(instance, Integer.valueOf(javaObjectID)); - weakInstances.put(javaObjectID, new WeakReference(instance)); + objectTable.weakenAndCheckAlive(javaObjectID); + } else { + objectTable.remove(javaObjectID); } - - strongInstances.remove(javaObjectID); - strongJavaObjectToID.remove(instance); } @RuntimeCallable @@ -1056,100 +1027,25 @@ private void makeInstanceWeak(ByteBuffer buff, int length, boolean keepAsWeak) { } } - @RuntimeCallable - private boolean makeInstanceWeakAndCheckIfAlive(int javaObjectID) { - if (logger.isEnabled()) { - logger.write("makeInstanceWeakAndCheckIfAlive instance " + javaObjectID); - } - Object instance = strongInstances.get(javaObjectID); - if (instance == null) { - WeakReference ref = weakInstances.get(javaObjectID); - if (ref == null) { - return false; - } else { - instance = ref.get(); - if (instance == null) { - // The Java was moved from strong to weak, and then the Java instance was collected. - weakInstances.remove(javaObjectID); - weakJavaObjectToID.remove(ref); - return false; - } else { - return true; - } - } - } else { - strongInstances.remove(javaObjectID); - strongJavaObjectToID.remove(instance); - - weakJavaObjectToID.put(instance, javaObjectID); - weakInstances.put(javaObjectID, new WeakReference(instance)); - - return true; - } - } - - @RuntimeCallable - private void checkWeakObjectAreAlive(ByteBuffer input, ByteBuffer output, int length) { - input.position(0); - output.position(0); - for (int i = 0; i < length; i++) { - int javaObjectId = input.getInt(); - - WeakReference weakRef = weakInstances.get(javaObjectId); - - int isReleased; - - if (weakRef != null) { - Object instance = weakRef.get(); - - if (instance == null) { - isReleased = 1; - weakInstances.remove(javaObjectId); - } else { - isReleased = 0; - } - } else { - isReleased = (strongInstances.get(javaObjectId) == null) ? 1 : 0; - } - - output.putInt(isReleased); - } - } - @RuntimeCallable private Object getJavaObjectByID(int javaObjectID) throws Exception { if (logger.isEnabled()) { logger.write("Platform.getJavaObjectByID:" + javaObjectID); } - Object instance = strongInstances.get(javaObjectID); - + Object instance = objectTable.get(javaObjectID); if (instance == null) { - instance = keyNotFoundObject; - } - - if (instance == keyNotFoundObject) { - WeakReference wr = weakInstances.get(javaObjectID); - if (wr == null) { - throw new NativeScriptException("No weak reference found. Attempt to use cleared object reference id=" + javaObjectID); - } - - instance = wr.get(); - if (instance == null) { - throw new NativeScriptException("Attempt to use cleared object reference id=" + javaObjectID); - } + throw new NativeScriptException(objectTable.contains(javaObjectID) + ? "Attempt to use cleared object reference id=" + javaObjectID + : "No weak reference found. Attempt to use cleared object reference id=" + javaObjectID); } return instance; } private Integer getJavaObjectID(Object obj) { - Integer id = strongJavaObjectToID.get(obj); - if (id == null) { - id = weakJavaObjectToID.get(obj); - } - - return id; + int id = objectTable.findId(obj); + return id == ObjectTable.NO_ID ? null : id; } @RuntimeCallable diff --git a/platforms/android/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java b/platforms/android/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java new file mode 100644 index 00000000..35107215 --- /dev/null +++ b/platforms/android/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java @@ -0,0 +1,305 @@ +package com.tns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +public class ObjectTableTest { + @Test + public void registersLooksUpAndRemoves() { + ObjectTable table = new ObjectTable(); + Object a = new Object(); + Object b = new Object(); + table.putStrong(7, a); + table.putStrong(9, b); + + assertEquals(7, table.findId(a)); + assertEquals(9, table.findId(b)); + assertSame(a, table.get(7)); + assertEquals(ObjectTable.NO_ID, table.findId(new Object())); + + table.remove(7); + assertEquals(ObjectTable.NO_ID, table.findId(a)); + assertNull(table.get(7)); + assertEquals(9, table.findId(b)); + assertEquals(1, table.size()); + } + + @Test + public void weakEntriesStayFindableWhileTheObjectLives() { + ObjectTable table = new ObjectTable(); + Object a = new Object(); + table.putStrong(1, a); + + assertTrue(table.weakenAndCheckAlive(1)); + assertSame(a, table.get(1)); + assertEquals(1, table.findId(a)); + assertTrue(table.weakenAndCheckAlive(1)); + assertFalse(table.weakenAndCheckAlive(2)); + } + + @Test + public void registeringAnIdAgainReplacesItsEntry() { + ObjectTable table = new ObjectTable(); + Object a = new Object(); + Object b = new Object(); + table.putStrong(5, a); + table.weakenAndCheckAlive(5); + table.putStrong(5, a); + assertEquals(1, table.size()); + assertSame(a, table.get(5)); + + table.putStrong(5, b); + assertEquals(1, table.size()); + assertSame(b, table.get(5)); + assertEquals(5, table.findId(b)); + assertEquals(ObjectTable.NO_ID, table.findId(a)); + } + + @Test + public void aRegisteredWeakReferenceIsNotMistakenForAWeakEntry() { + ObjectTable table = new ObjectTable(); + java.lang.ref.WeakReference ref = new java.lang.ref.WeakReference<>(new Object()); + table.putStrong(3, ref); + + assertSame(ref, table.get(3)); + assertEquals(3, table.findId(ref)); + } + + @Test + public void concurrentRegistrationsAgreeOnOneIdPerObject() throws Exception { + final ObjectTable table = new ObjectTable(true); + final java.util.concurrent.atomic.AtomicInteger nextId = new java.util.concurrent.atomic.AtomicInteger(); + final ObjectTable.IdSource ids = new ObjectTable.IdSource() { + @Override + public int newId() { + return nextId.getAndIncrement(); + } + }; + final int objectCount = 5000; + final Object[] objects = new Object[objectCount]; + for (int i = 0; i < objectCount; i++) { + objects[i] = new Object(); + } + final int threadCount = 6; + final int[][] seen = new int[threadCount][objectCount]; + final int[] freshCounts = new int[threadCount]; + final java.util.concurrent.CountDownLatch go = new java.util.concurrent.CountDownLatch(1); + Thread[] threads = new Thread[threadCount]; + for (int t = 0; t < threadCount; t++) { + final int index = t; + threads[t] = new Thread(new Runnable() { + @Override + public void run() { + Random random = new Random(index); + try { + go.await(); + } catch (InterruptedException e) { + return; + } + for (int n = 0; n < objectCount; n++) { + int i = (n * 7 + index * 131 + random.nextInt(3)) % objectCount; + long found = table.findOrRegister(objects[i], ids); + if ((found & ObjectTable.FRESH) != 0) { + freshCounts[index]++; + } + seen[index][i] = (int) found + 1; + } + } + }); + threads[t].start(); + } + go.countDown(); + for (Thread thread : threads) { + thread.join(); + } + + int fresh = 0; + for (int count : freshCounts) { + fresh += count; + } + assertEquals(table.size(), fresh); + for (int i = 0; i < objectCount; i++) { + int id = table.findId(objects[i]); + for (int t = 0; t < threadCount; t++) { + if (seen[t][i] != 0) { + assertEquals(id, seen[t][i] - 1); + } + } + } + } + + @Test + public void exactReadsStayExactWhileAnotherThreadRegisters() throws Exception { + final ObjectTable table = new ObjectTable(true); + final java.util.concurrent.atomic.AtomicInteger nextId = new java.util.concurrent.atomic.AtomicInteger(1000); + final ObjectTable.IdSource ids = new ObjectTable.IdSource() { + @Override + public int newId() { + return nextId.getAndIncrement(); + } + }; + final int stableCount = 64; + final Object[] stable = new Object[stableCount]; + for (int i = 0; i < stableCount; i++) { + stable[i] = new Object(); + table.putStrong(i, stable[i]); + } + final java.util.concurrent.atomic.AtomicBoolean done = new java.util.concurrent.atomic.AtomicBoolean(); + final java.util.concurrent.atomic.AtomicReference failure = new java.util.concurrent.atomic.AtomicReference<>(); + + Thread writer = new Thread(new Runnable() { + @Override + public void run() { + List churn = new ArrayList<>(); + Random random = new Random(3); + while (!done.get()) { + if (churn.size() < 20_000 && random.nextInt(3) != 0) { + churn.add((int) table.findOrRegister(new Object(), ids)); + } else if (!churn.isEmpty()) { + table.remove(churn.remove(churn.size() - 1)); + } + } + } + }); + Thread reader = new Thread(new Runnable() { + @Override + public void run() { + Random random = new Random(5); + while (!done.get()) { + int i = random.nextInt(stableCount); + int id = table.findId(stable[i]); + if (id != i) { + failure.compareAndSet(null, "findId: expected " + i + ", got " + id); + } + if (table.get(i) != stable[i]) { + failure.compareAndSet(null, "get(" + i + ") returned another object"); + } + if (!table.contains(i)) { + failure.compareAndSet(null, "contains(" + i + ") was false"); + } + } + } + }); + writer.start(); + reader.start(); + Thread.sleep(2000); + done.set(true); + writer.join(); + reader.join(); + + assertNull(failure.get(), failure.get()); + } + + @Test + public void keepsSurvivorsOfReleasedRangesAndOldIdsRegisteredLate() { + ObjectTable table = new ObjectTable(); + Object[] objects = new Object[3000]; + for (int id = 0; id < objects.length; id++) { + objects[id] = new Object(); + table.putStrong(id, objects[id]); + } + for (int id = 0; id < 2048; id++) { + if (id != 5 && id != 1500) { + table.remove(id); + } + } + + assertTrue(table.weakenAndCheckAlive(5)); + assertSame(objects[5], table.get(5)); + assertEquals(5, table.findId(objects[5])); + assertEquals(1500, table.findId(objects[1500])); + + Object late = new Object(); + table.putStrong(700, late); + assertSame(late, table.get(700)); + assertEquals(700, table.findId(late)); + + table.remove(5); + assertNull(table.get(5)); + assertFalse(table.contains(5)); + assertEquals(ObjectTable.NO_ID, table.findId(objects[5])); + assertEquals(954, table.size()); + } + + @Test + public void idsPastIntMaxAreUnsigned() { + ObjectTable table = new ObjectTable(true); + Object a = new Object(); + Object b = new Object(); + table.putStrong(Integer.MIN_VALUE + 3, a); + + assertSame(a, table.get(Integer.MIN_VALUE + 3)); + assertEquals(Integer.MIN_VALUE + 3, table.findId(a)); + assertTrue(table.weakenAndCheckAlive(Integer.MIN_VALUE + 3)); + + long found = table.findOrRegister(b, new ObjectTable.IdSource() { + @Override + public int newId() { + return -7; + } + }); + assertTrue((found & ObjectTable.FRESH) != 0); + assertEquals(-7, (int) found); + assertEquals(-7, table.findId(b)); + assertEquals(-7L & 0xFFFFFFFFL, table.findOrRegister(b, null)); + + table.remove(-7); + assertNull(table.get(-7)); + assertEquals(ObjectTable.NO_ID, table.findId(b)); + assertEquals(1, table.size()); + } + + @Test + public void matchesReferenceMapsUnderRandomOperations() { + Random random = new Random(42); + ObjectTable table = new ObjectTable(); + Map byId = new HashMap<>(); + Map byObject = new IdentityHashMap<>(); + List live = new ArrayList<>(); + int nextId = 0; + + for (int step = 0; step < 200_000; step++) { + int op = random.nextInt(10); + if (op < 5 || live.isEmpty()) { + Object obj = new Object(); + int id = nextId++; + table.putStrong(id, obj); + byId.put(id, obj); + byObject.put(obj, id); + live.add(id); + } else if (op < 8) { + int id = live.get(random.nextInt(live.size())); + Object obj = byId.get(id); + assertEquals(id, table.findId(obj)); + assertSame(obj, table.get(id)); + } else { + int index = random.nextInt(live.size()); + int id = live.get(index); + live.set(index, live.get(live.size() - 1)); + live.remove(live.size() - 1); + Object obj = byId.remove(id); + byObject.remove(obj); + table.remove(id); + assertEquals(ObjectTable.NO_ID, table.findId(obj)); + assertNull(table.get(id)); + } + } + + assertEquals(byId.size(), table.size()); + for (Map.Entry entry : byObject.entrySet()) { + assertEquals((int) entry.getValue(), table.findId(entry.getKey())); + } + } +} \ No newline at end of file diff --git a/platforms/android/test-app/runtime/src/test/java/com/tns/RuntimeTest.java b/platforms/android/test-app/runtime/src/test/java/com/tns/RuntimeTest.java index 265062ce..3249cecb 100644 --- a/platforms/android/test-app/runtime/src/test/java/com/tns/RuntimeTest.java +++ b/platforms/android/test-app/runtime/src/test/java/com/tns/RuntimeTest.java @@ -1,22 +1,11 @@ package com.tns; -import org.junit.Assert; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; + import org.junit.Before; import org.junit.Test; -import org.mockito.Mock; - -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; - -import java.lang.ref.WeakReference; -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockingDetails; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; public class RuntimeTest { @@ -24,67 +13,39 @@ public class RuntimeTest { private static final Object TESTING_NATIVE_OBJECT = new Object(); private Runtime runtime; - - @Mock - private HashMap strongInstances; - - @Mock - private HashMap> weakInstances; - - @Mock - private NativeScriptHashMap strongJavaObjectToId; - - @Mock - private NativeScriptWeakHashMap weakJavaObjectToId; - - @Mock - private WeakReference testingObjectWeakRefMock; + private ObjectTable objectTable; @Before public void setUp() { - MockitoAnnotations.initMocks(this); + objectTable = new ObjectTable(); runtime = new Runtime(mock(ClassResolver.class), mock(GcListener.class), mock(StaticConfiguration.class), mock(DynamicConfiguration.class), 0, 0, - strongInstances, - weakInstances, - strongJavaObjectToId, - weakJavaObjectToId); + objectTable); } @Test public void testStrongInstanceIsSuccessfullyRemoved() { - when(strongInstances.get(TESTING_NATIVE_OBJECT_ID)).thenReturn(TESTING_NATIVE_OBJECT); - - runtime.releaseNativeCounterpart(TESTING_NATIVE_OBJECT_ID); - - verify(strongInstances).remove(TESTING_NATIVE_OBJECT_ID); - verify(strongJavaObjectToId).remove(TESTING_NATIVE_OBJECT); - } - - @Test - public void testWeakInstanceIsSuccessfullyRemoved(){ - when(weakInstances.get(TESTING_NATIVE_OBJECT_ID)).thenReturn(testingObjectWeakRefMock); + objectTable.putStrong(TESTING_NATIVE_OBJECT_ID, TESTING_NATIVE_OBJECT); runtime.releaseNativeCounterpart(TESTING_NATIVE_OBJECT_ID); - verify(weakInstances).remove(TESTING_NATIVE_OBJECT_ID); - verify(weakJavaObjectToId).remove(testingObjectWeakRefMock); + assertNull(objectTable.get(TESTING_NATIVE_OBJECT_ID)); + assertEquals(ObjectTable.NO_ID, objectTable.findId(TESTING_NATIVE_OBJECT)); } @Test - public void testStrongAndWeakInstancesAreSuccessfullyRemoved(){ - when(strongInstances.get(TESTING_NATIVE_OBJECT_ID)).thenReturn(TESTING_NATIVE_OBJECT); - when(weakInstances.get(TESTING_NATIVE_OBJECT_ID)).thenReturn(testingObjectWeakRefMock); + public void testWeakInstanceIsSuccessfullyRemoved() { + objectTable.putStrong(TESTING_NATIVE_OBJECT_ID, TESTING_NATIVE_OBJECT); + objectTable.weakenAndCheckAlive(TESTING_NATIVE_OBJECT_ID); runtime.releaseNativeCounterpart(TESTING_NATIVE_OBJECT_ID); - verify(strongInstances).remove(TESTING_NATIVE_OBJECT_ID); - verify(strongJavaObjectToId).remove(TESTING_NATIVE_OBJECT); - verify(weakInstances).remove(TESTING_NATIVE_OBJECT_ID); - verify(weakJavaObjectToId).remove(testingObjectWeakRefMock); + assertNull(objectTable.get(TESTING_NATIVE_OBJECT_ID)); + assertEquals(ObjectTable.NO_ID, objectTable.findId(TESTING_NATIVE_OBJECT)); + assertEquals(0, objectTable.size()); } } From 0765188f92b84a11f76476b74103ac9d70ce8780 Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 09:49:37 +0500 Subject: [PATCH 07/16] perf(android): hand finalized object ids to Java in one batched upcall --- .../jni/jsi/objectmanager/ObjectManager.cpp | 65 +++++++++------- .../ffi/jni/jsi/objectmanager/ObjectManager.h | 12 ++- .../jni/napi/objectmanager/ObjectManager.cpp | 78 +++++++++---------- .../jni/napi/objectmanager/ObjectManager.h | 12 ++- .../src/main/java/com/tns/Runtime.java | 24 +----- 5 files changed, 93 insertions(+), 98 deletions(-) diff --git a/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.cpp b/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.cpp index 86ebb7aa..c570228e 100644 --- a/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.cpp +++ b/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.cpp @@ -39,13 +39,9 @@ ObjectManager::ObjectManager(jobject javaRuntimeObject) : "(Ljava/lang/Object;)I"); assert(GET_OR_CREATE_JAVA_OBJECT_ID_METHOD_ID != nullptr); - MAKE_INSTANCE_WEAK_METHOD_ID = env.GetMethodID(runtimeClass, "makeInstanceWeak", - "(I)V"); - assert(MAKE_INSTANCE_WEAK_METHOD_ID != nullptr); - - MAKE_INSTANCE_WEAK_BATCH_METHOD_ID = env.GetMethodID(runtimeClass, "makeInstanceWeak", - "(Ljava/nio/ByteBuffer;IZ)V"); - assert(MAKE_INSTANCE_WEAK_BATCH_METHOD_ID != nullptr); + MAKE_INSTANCES_WEAK_METHOD_ID = env.GetMethodID(runtimeClass, "makeInstancesWeak", + "([II)V"); + assert(MAKE_INSTANCES_WEAK_METHOD_ID != nullptr); MAKE_INSTANCE_STRONG_METHOD_ID = env.GetMethodID(runtimeClass, "makeInstanceStrong", "(I)V"); @@ -490,16 +486,7 @@ void ObjectManager::HostObjectProxyPostFinalizer(JsRuntime &rt, void *data, void // instance weak on collection. if (pending->isPrimary && pending->instanceInfo) { if (!destroying) { - auto objManager = rtOwner->GetObjectManager(); - auto javaObjectID = pending->instanceInfo->JavaObjectID; - if (objManager->m_weakObjectIds.find(javaObjectID) == - objManager->m_weakObjectIds.end()) { - objManager->m_weakObjectIds.emplace(javaObjectID); - JEnv jEnv; - jEnv.CallVoidMethod(objManager->m_javaRuntimeObject, - objManager->MAKE_INSTANCE_WEAK_METHOD_ID, - javaObjectID); - } + rtOwner->GetObjectManager()->MarkInstanceWeak(pending->instanceInfo->JavaObjectID); } delete pending->instanceInfo; } @@ -676,10 +663,38 @@ JsValue ObjectManager::CreateJSWrapper(jint javaObjectID, MetadataNode *node, jc return proxy; } +void ObjectManager::MarkInstanceWeak(int javaObjectID) { + if (!m_weakObjectIds.emplace(javaObjectID).second) return; + m_pendingWeakIds.insert(javaObjectID); + if (m_flushPosted) return; + m_flushPosted = true; + Runtime::PostFinalizer(*m_rt, FlushWeakIdsCallback, nullptr, nullptr); +} + +void ObjectManager::FlushWeakIdsCallback(JsRuntime &rt, void *, void *) { + auto rtOwner = Runtime::GetRuntimeUnchecked(rt); + if (rtOwner == nullptr || rtOwner->is_destroying) return; + rtOwner->GetObjectManager()->FlushWeakIds(); +} + +void ObjectManager::FlushWeakIds() { + m_flushPosted = false; + if (m_pendingWeakIds.empty()) return; + + JEnv jenv; + jsize count = static_cast(m_pendingWeakIds.size()); + JniLocalRef ids(jenv.NewIntArray(count)); + std::vector buffer(m_pendingWeakIds.begin(), m_pendingWeakIds.end()); + m_pendingWeakIds.clear(); + jenv.SetIntArrayRegion(ids, 0, count, buffer.data()); + jenv.CallVoidMethod(m_javaRuntimeObject, MAKE_INSTANCES_WEAK_METHOD_ID, (jintArray) ids, count); +} + void ObjectManager::EnsureInstanceStrong(int javaObjectID) { auto it = m_weakObjectIds.find(javaObjectID); if (it == m_weakObjectIds.end()) return; m_weakObjectIds.erase(it); + if (m_pendingWeakIds.erase(javaObjectID) != 0) return; JEnv jenv; jenv.CallVoidMethod(m_javaRuntimeObject, MAKE_INSTANCE_STRONG_METHOD_ID, javaObjectID); DEBUG_WRITE("Making instance strong: %d", javaObjectID); @@ -740,12 +755,7 @@ void ObjectManager::WrapperPostFinalizer(JsRuntime &rt, void *data, void *hint) !js_util::is_null_or_undefined(objManager->LockWrapper(it->second))) { return; } - if (objManager->m_weakObjectIds.find(javaObjectID) == objManager->m_weakObjectIds.end()) { - objManager->m_weakObjectIds.emplace(javaObjectID); - JEnv jEnv; - jEnv.CallVoidMethod(objManager->m_javaRuntimeObject, objManager->MAKE_INSTANCE_WEAK_METHOD_ID, - javaObjectID); - } + objManager->MarkInstanceWeak(javaObjectID); if (it != objManager->m_idToObject.end()) objManager->m_idToObject.erase(it); } @@ -829,13 +839,8 @@ void ObjectManager::ReleaseObjectNow(JsRuntime &rt, int javaObjectId) { if (!rtOwner || rtOwner->is_destroying) return; ObjectManager *objMgr = rtOwner->GetObjectManager(); - auto itFound = objMgr->m_weakObjectIds.find(javaObjectId); - if (itFound == objMgr->m_weakObjectIds.end()) { - JEnv jEnv; - jEnv.CallVoidMethod(objMgr->m_javaRuntimeObject, objMgr->MAKE_INSTANCE_WEAK_METHOD_ID, - javaObjectId); - objMgr->m_weakObjectIds.emplace(javaObjectId); - } + objMgr->MarkInstanceWeak(javaObjectId); + objMgr->FlushWeakIds(); objMgr->m_idToProxy.erase(javaObjectId); objMgr->m_idToObject.erase(javaObjectId); diff --git a/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.h b/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.h index f49d134f..e8a9e53e 100644 --- a/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.h +++ b/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.h @@ -216,6 +216,12 @@ namespace tns { void EnsureInstanceStrong(int javaObjectID); + void MarkInstanceWeak(int javaObjectID); + + void FlushWeakIds(); + + static void FlushWeakIdsCallback(JsRuntime &rt, void *data, void *hint); + static void WrapperPostFinalizer(JsRuntime &rt, void *data, void *hint); jweak GetJavaObjectByID(uint32_t javaObjectID); @@ -248,6 +254,8 @@ namespace tns { std::shared_ptr m_ownerToken; robin_hood::unordered_set m_weakObjectIds; robin_hood::unordered_set m_markedAsWeakIds; + robin_hood::unordered_set m_pendingWeakIds; + bool m_flushPosted = false; // Every live host-object proxy. The engine owns the proxies, so without // this the only thing that ever destroys them is the engine's own @@ -278,9 +286,7 @@ namespace tns { jmethodID GET_OR_CREATE_JAVA_OBJECT_ID_METHOD_ID; - jmethodID MAKE_INSTANCE_WEAK_BATCH_METHOD_ID; - - jmethodID MAKE_INSTANCE_WEAK_METHOD_ID; + jmethodID MAKE_INSTANCES_WEAK_METHOD_ID; jmethodID MAKE_INSTANCE_STRONG_METHOD_ID; diff --git a/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.cpp b/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.cpp index 4558eb36..1a0dc5a6 100644 --- a/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.cpp +++ b/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.cpp @@ -39,13 +39,9 @@ ObjectManager::ObjectManager(jobject javaRuntimeObject) : "(Ljava/lang/Object;)I"); assert(GET_OR_CREATE_JAVA_OBJECT_ID_METHOD_ID != nullptr); - MAKE_INSTANCE_WEAK_METHOD_ID = env.GetMethodID(runtimeClass, "makeInstanceWeak", - "(I)V"); - assert(MAKE_INSTANCE_WEAK_METHOD_ID != nullptr); - - MAKE_INSTANCE_WEAK_BATCH_METHOD_ID = env.GetMethodID(runtimeClass, "makeInstanceWeak", - "(Ljava/nio/ByteBuffer;IZ)V"); - assert(MAKE_INSTANCE_WEAK_BATCH_METHOD_ID != nullptr); + MAKE_INSTANCES_WEAK_METHOD_ID = env.GetMethodID(runtimeClass, "makeInstancesWeak", + "([II)V"); + assert(MAKE_INSTANCES_WEAK_METHOD_ID != nullptr); MAKE_INSTANCE_STRONG_METHOD_ID = env.GetMethodID(runtimeClass, "makeInstanceStrong", "(I)V"); @@ -641,16 +637,7 @@ void ObjectManager::HostObjectProxyPostFinalizer(napi_env env, void *data, // instance weak on collection (the old JSObjectProxyFinalizerCallback role). if (proxy->isPrimary && proxy->instanceInfo) { if (!destroying) { - auto objManager = rt->GetObjectManager(); - auto javaObjectID = proxy->instanceInfo->JavaObjectID; - if (objManager->m_weakObjectIds.find(javaObjectID) == - objManager->m_weakObjectIds.end()) { - objManager->m_weakObjectIds.emplace(javaObjectID); - JEnv jEnv; - jEnv.CallVoidMethod(objManager->m_javaRuntimeObject, - objManager->MAKE_INSTANCE_WEAK_METHOD_ID, - javaObjectID); - } + rt->GetObjectManager()->MarkInstanceWeak(proxy->instanceInfo->JavaObjectID); } delete proxy->instanceInfo; } @@ -854,10 +841,38 @@ napi_value ObjectManager::CreateJSWrapper(jint javaObjectID, MetadataNode *node, return proxy; } +void ObjectManager::MarkInstanceWeak(int javaObjectID) { + if (!m_weakObjectIds.emplace(javaObjectID).second) return; + m_pendingWeakIds.insert(javaObjectID); + if (m_flushPosted) return; + m_flushPosted = true; + Runtime::PostFinalizer(m_env, FlushWeakIdsCallback, nullptr, nullptr); +} + +void ObjectManager::FlushWeakIdsCallback(napi_env env, void *, void *) { + auto rt = Runtime::GetRuntimeUnchecked(env); + if (rt == nullptr || rt->is_destroying) return; + rt->GetObjectManager()->FlushWeakIds(); +} + +void ObjectManager::FlushWeakIds() { + m_flushPosted = false; + if (m_pendingWeakIds.empty()) return; + + JEnv jenv; + jsize count = static_cast(m_pendingWeakIds.size()); + JniLocalRef ids(jenv.NewIntArray(count)); + std::vector buffer(m_pendingWeakIds.begin(), m_pendingWeakIds.end()); + m_pendingWeakIds.clear(); + jenv.SetIntArrayRegion(ids, 0, count, buffer.data()); + jenv.CallVoidMethod(m_javaRuntimeObject, MAKE_INSTANCES_WEAK_METHOD_ID, (jintArray) ids, count); +} + void ObjectManager::EnsureInstanceStrong(int javaObjectID) { auto it = m_weakObjectIds.find(javaObjectID); if (it == m_weakObjectIds.end()) return; m_weakObjectIds.erase(it); + if (m_pendingWeakIds.erase(javaObjectID) != 0) return; JEnv jenv; jenv.CallVoidMethod(m_javaRuntimeObject, MAKE_INSTANCE_STRONG_METHOD_ID, javaObjectID); DEBUG_WRITE("Making instance strong: %d", javaObjectID); @@ -971,12 +986,8 @@ void ObjectManager::JSObjectPostFinalizerCallback(napi_env env, void *finalizeDa objManager->m_idToObject.erase(it); } } - if (!replaced && objManager->m_weakObjectIds.find(data->JavaObjectID) == - objManager->m_weakObjectIds.end()) { - objManager->m_weakObjectIds.emplace(data->JavaObjectID); - JEnv jEnv; - jEnv.CallVoidMethod(objManager->m_javaRuntimeObject, - objManager->MAKE_INSTANCE_WEAK_METHOD_ID, data->JavaObjectID); + if (!replaced) { + objManager->MarkInstanceWeak(data->JavaObjectID); } } delete data; @@ -996,18 +1007,8 @@ void ObjectManager::JSObjectProxyFinalizerCallback(napi_env env, void *finalizeD auto rt = Runtime::GetRuntimeUnchecked(env); if (rt && !rt->is_destroying) { - auto objManager = rt->GetObjectManager(); - auto itFound = objManager->m_weakObjectIds.find(state->JavaObjectID); - DEBUG_WRITE("JS Proxy finalizer called for object id: %d", state->JavaObjectID); - if (itFound == objManager->m_weakObjectIds.end()) { - objManager->m_weakObjectIds.emplace(state->JavaObjectID); - JEnv jEnv; - jEnv.CallVoidMethod(objManager->m_javaRuntimeObject, - objManager->MAKE_INSTANCE_WEAK_METHOD_ID, - state->JavaObjectID); - - } + rt->GetObjectManager()->MarkInstanceWeak(state->JavaObjectID); } delete state; } @@ -1082,13 +1083,8 @@ void ObjectManager::ReleaseObjectNow(napi_env env, int javaObjectId) { if (!rt || rt->is_destroying) return; ObjectManager *objMgr = rt->GetObjectManager(); - auto itFound = objMgr->m_weakObjectIds.find(javaObjectId); - if (itFound == objMgr->m_weakObjectIds.end()) { - JEnv jEnv; - jEnv.CallVoidMethod(objMgr->m_javaRuntimeObject, objMgr->MAKE_INSTANCE_WEAK_METHOD_ID, - javaObjectId); - objMgr->m_weakObjectIds.emplace(javaObjectId); - } + objMgr->MarkInstanceWeak(javaObjectId); + objMgr->FlushWeakIds(); auto found = objMgr->m_idToProxy.find(javaObjectId); if (found != objMgr->m_idToProxy.end()) { diff --git a/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.h b/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.h index 4e4af967..ad8e328f 100644 --- a/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.h +++ b/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.h @@ -176,6 +176,12 @@ namespace tns { void EnsureInstanceStrong(int javaObjectID); + void MarkInstanceWeak(int javaObjectID); + + void FlushWeakIds(); + + static void FlushWeakIdsCallback(napi_env env, void *data, void *hint); + static void JSObjectProxyFinalizerCallback(napi_env env, void *finalizeData, void *finalizeHint); @@ -197,6 +203,8 @@ namespace tns { robin_hood::unordered_map m_idToObject; robin_hood::unordered_set m_weakObjectIds; robin_hood::unordered_set m_markedAsWeakIds; + robin_hood::unordered_set m_pendingWeakIds; + bool m_flushPosted = false; LRUCache m_cache; @@ -214,9 +222,7 @@ namespace tns { jmethodID GET_OR_CREATE_JAVA_OBJECT_ID_METHOD_ID; - jmethodID MAKE_INSTANCE_WEAK_BATCH_METHOD_ID; - - jmethodID MAKE_INSTANCE_WEAK_METHOD_ID; + jmethodID MAKE_INSTANCES_WEAK_METHOD_ID; jmethodID MAKE_INSTANCE_STRONG_METHOD_ID; diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java index 8f0ef942..740a2c1d 100644 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -20,7 +20,6 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; @@ -1003,28 +1002,11 @@ private void makeInstanceStrong(int objectId) { } @RuntimeCallable - private void makeInstanceWeak(int javaObjectID) { - this.makeInstanceWeak(javaObjectID, true); - } - - private void makeInstanceWeak(int javaObjectID, boolean keepAsWeak) { + private void makeInstancesWeak(int[] objectIds, int count) { if (logger.isEnabled()) { - logger.write("makeInstanceWeak instance " + javaObjectID + " keepAsWeak=" + keepAsWeak); - } - if (keepAsWeak) { - objectTable.weakenAndCheckAlive(javaObjectID); - } else { - objectTable.remove(javaObjectID); - } - } - - @RuntimeCallable - private void makeInstanceWeak(ByteBuffer buff, int length, boolean keepAsWeak) { - buff.position(0); - for (int i = 0; i < length; i++) { - int javaObjectId = buff.getInt(); - makeInstanceWeak(javaObjectId, keepAsWeak); + logger.write("makeInstancesWeak count=" + count); } + objectTable.weakenAndCheckAlive(objectIds, count); } @RuntimeCallable From da5aebc2802619ee1a4e491bc501d951d0bd2d4f Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 09:49:37 +0500 Subject: [PATCH 08/16] perf(android): register a constructed instance and read the heap size in one upcall --- .../jni/jsi/callbackhandlers/CallbackHandlers.cpp | 12 ++++++------ .../ffi/jni/jsi/callbackhandlers/CallbackHandlers.h | 2 +- .../jni/napi/callbackhandlers/CallbackHandlers.cpp | 12 ++++++------ .../ffi/jni/napi/callbackhandlers/CallbackHandlers.h | 2 +- NativeScript/runtime/android/jsi/Runtime.cpp | 5 ++++- NativeScript/runtime/android/jsi/Runtime.h | 2 ++ NativeScript/runtime/android/napi/Runtime.cpp | 5 ++++- NativeScript/runtime/android/napi/Runtime.h | 2 ++ .../runtime/src/main/java/com/tns/Runtime.java | 6 ++++++ 9 files changed, 32 insertions(+), 16 deletions(-) diff --git a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp index a5218b37..aad2f5a3 100644 --- a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp @@ -112,9 +112,9 @@ void CallbackHandlers::Init(JsRuntime &rt) { CURRENT_OBJECTID_FIELD_ID = jEnv.GetFieldID(RUNTIME_CLASS, "currentObjectId", "I"); assert(CURRENT_OBJECTID_FIELD_ID != nullptr); - MAKE_INSTANCE_STRONG_ID = jEnv.GetMethodID(RUNTIME_CLASS, "makeInstanceStrong", - "(Ljava/lang/Object;I)V"); - assert(MAKE_INSTANCE_STRONG_ID != nullptr); + REGISTER_CONSTRUCTED_INSTANCE_ID = jEnv.GetMethodID(RUNTIME_CLASS, "registerConstructedInstance", + "(Ljava/lang/Object;I)J"); + assert(REGISTER_CONSTRUCTED_INSTANCE_ID != nullptr); GET_TYPE_METADATA = jEnv.GetStaticMethodID(RUNTIME_CLASS, "getTypeMetadata", "(Ljava/lang/String;I)[Ljava/lang/String;"); @@ -601,10 +601,10 @@ bool CallbackHandlers::RegisterInstance(JsRuntime &rt, const JsValue &jsObject, } } - jEnv.CallVoidMethod(runtime->GetJavaRuntime(), MAKE_INSTANCE_STRONG_ID, instance, javaObjectID); + jlong usedMemory = jEnv.CallLongMethod(runtime->GetJavaRuntime(), REGISTER_CONSTRUCTED_INSTANCE_ID, instance, javaObjectID); // Reuse the runtime we already resolved instead of re-querying via rt. - runtime->AdjustAmountOfExternalAllocatedMemory(); + runtime->AdjustAmountOfExternalAllocatedMemory(usedMemory); runtime->TryCallGC(); JniLocalRef localInstance(instance); @@ -1807,7 +1807,7 @@ jclass CallbackHandlers::RUNTIME_CLASS = nullptr; jclass CallbackHandlers::JAVA_LANG_STRING = nullptr; jfieldID CallbackHandlers::CURRENT_OBJECTID_FIELD_ID = nullptr; jmethodID CallbackHandlers::RESOLVE_CLASS_METHOD_ID = nullptr; -jmethodID CallbackHandlers::MAKE_INSTANCE_STRONG_ID = nullptr; +jmethodID CallbackHandlers::REGISTER_CONSTRUCTED_INSTANCE_ID = nullptr; jmethodID CallbackHandlers::GET_TYPE_METADATA = nullptr; jmethodID CallbackHandlers::ENABLE_VERBOSE_LOGGING_METHOD_ID = nullptr; jmethodID CallbackHandlers::DISABLE_VERBOSE_LOGGING_METHOD_ID = nullptr; diff --git a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h index b2f99eba..97ad6de7 100644 --- a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h +++ b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h @@ -251,7 +251,7 @@ namespace tns { static jfieldID CURRENT_OBJECTID_FIELD_ID; - static jmethodID MAKE_INSTANCE_STRONG_ID; + static jmethodID REGISTER_CONSTRUCTED_INSTANCE_ID; static jmethodID GET_TYPE_METADATA; diff --git a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp index 6e04499f..003173d4 100644 --- a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp @@ -98,9 +98,9 @@ void CallbackHandlers::Init(napi_env env) { CURRENT_OBJECTID_FIELD_ID = jEnv.GetFieldID(RUNTIME_CLASS, "currentObjectId", "I"); assert(CURRENT_OBJECTID_FIELD_ID != nullptr); - MAKE_INSTANCE_STRONG_ID = jEnv.GetMethodID(RUNTIME_CLASS, "makeInstanceStrong", - "(Ljava/lang/Object;I)V"); - assert(MAKE_INSTANCE_STRONG_ID != nullptr); + REGISTER_CONSTRUCTED_INSTANCE_ID = jEnv.GetMethodID(RUNTIME_CLASS, "registerConstructedInstance", + "(Ljava/lang/Object;I)J"); + assert(REGISTER_CONSTRUCTED_INSTANCE_ID != nullptr); GET_TYPE_METADATA = jEnv.GetStaticMethodID(RUNTIME_CLASS, "getTypeMetadata", "(Ljava/lang/String;I)[Ljava/lang/String;"); @@ -615,10 +615,10 @@ bool CallbackHandlers::RegisterInstance(napi_env env, napi_value jsObject, } } - jEnv.CallVoidMethod(runtime->GetJavaRuntime(), MAKE_INSTANCE_STRONG_ID, instance, javaObjectID); + jlong usedMemory = jEnv.CallLongMethod(runtime->GetJavaRuntime(), REGISTER_CONSTRUCTED_INSTANCE_ID, instance, javaObjectID); // Reuse the runtime we already resolved instead of re-querying via env. - runtime->AdjustAmountOfExternalAllocatedMemory(); + runtime->AdjustAmountOfExternalAllocatedMemory(usedMemory); runtime->TryCallGC(); JniLocalRef localInstance(instance); @@ -1905,7 +1905,7 @@ jclass CallbackHandlers::RUNTIME_CLASS = nullptr; jclass CallbackHandlers::JAVA_LANG_STRING = nullptr; jfieldID CallbackHandlers::CURRENT_OBJECTID_FIELD_ID = nullptr; jmethodID CallbackHandlers::RESOLVE_CLASS_METHOD_ID = nullptr; -jmethodID CallbackHandlers::MAKE_INSTANCE_STRONG_ID = nullptr; +jmethodID CallbackHandlers::REGISTER_CONSTRUCTED_INSTANCE_ID = nullptr; jmethodID CallbackHandlers::GET_TYPE_METADATA = nullptr; jmethodID CallbackHandlers::ENABLE_VERBOSE_LOGGING_METHOD_ID = nullptr; jmethodID CallbackHandlers::DISABLE_VERBOSE_LOGGING_METHOD_ID = nullptr; diff --git a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h index 68934b43..66402073 100644 --- a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h +++ b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h @@ -229,7 +229,7 @@ namespace tns { static jfieldID CURRENT_OBJECTID_FIELD_ID; - static jmethodID MAKE_INSTANCE_STRONG_ID; + static jmethodID REGISTER_CONSTRUCTED_INSTANCE_ID; static jmethodID GET_TYPE_METADATA; diff --git a/NativeScript/runtime/android/jsi/Runtime.cpp b/NativeScript/runtime/android/jsi/Runtime.cpp index 19d35863..702157a0 100644 --- a/NativeScript/runtime/android/jsi/Runtime.cpp +++ b/NativeScript/runtime/android/jsi/Runtime.cpp @@ -613,7 +613,10 @@ bool Runtime::NotifyGC(JNIEnv *jEnv, jobject obj, jintArray object_ids) { void Runtime::AdjustAmountOfExternalAllocatedMemory() { JEnv jEnv; - int64_t usedMemory = jEnv.CallLongMethod(m_runtime, GET_USED_MEMORY_METHOD_ID); + AdjustAmountOfExternalAllocatedMemory(jEnv.CallLongMethod(m_runtime, GET_USED_MEMORY_METHOD_ID)); +} + +void Runtime::AdjustAmountOfExternalAllocatedMemory(int64_t usedMemory) { int64_t changeInBytes = usedMemory - m_lastUsedMemory; int64_t externalMemory = 0; diff --git a/NativeScript/runtime/android/jsi/Runtime.h b/NativeScript/runtime/android/jsi/Runtime.h index 51084b11..39a64fff 100644 --- a/NativeScript/runtime/android/jsi/Runtime.h +++ b/NativeScript/runtime/android/jsi/Runtime.h @@ -183,6 +183,8 @@ namespace tns { void AdjustAmountOfExternalAllocatedMemory(); + void AdjustAmountOfExternalAllocatedMemory(int64_t usedMemory); + JSMethodCache *js_method_cache; bool is_destroying = false; diff --git a/NativeScript/runtime/android/napi/Runtime.cpp b/NativeScript/runtime/android/napi/Runtime.cpp index 771a95e0..51c43038 100644 --- a/NativeScript/runtime/android/napi/Runtime.cpp +++ b/NativeScript/runtime/android/napi/Runtime.cpp @@ -531,7 +531,10 @@ bool Runtime::NotifyGC(JNIEnv *jEnv, jobject obj, jintArray object_ids) { void Runtime::AdjustAmountOfExternalAllocatedMemory() { JEnv jEnv; - int64_t usedMemory = jEnv.CallLongMethod(m_runtime, GET_USED_MEMORY_METHOD_ID); + AdjustAmountOfExternalAllocatedMemory(jEnv.CallLongMethod(m_runtime, GET_USED_MEMORY_METHOD_ID)); +} + +void Runtime::AdjustAmountOfExternalAllocatedMemory(int64_t usedMemory) { int64_t changeInBytes = usedMemory - m_lastUsedMemory; int64_t externalMemory = 0; diff --git a/NativeScript/runtime/android/napi/Runtime.h b/NativeScript/runtime/android/napi/Runtime.h index 77b25f96..87ed3caa 100644 --- a/NativeScript/runtime/android/napi/Runtime.h +++ b/NativeScript/runtime/android/napi/Runtime.h @@ -150,6 +150,8 @@ namespace tns { void AdjustAmountOfExternalAllocatedMemory(); + void AdjustAmountOfExternalAllocatedMemory(int64_t usedMemory); + JSMethodCache *js_method_cache; bool is_destroying = false; diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java index 740a2c1d..89be95c6 100644 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -967,6 +967,12 @@ private static String getTypeMetadata(Class clazz) { return ret; } + @RuntimeCallable + private long registerConstructedInstance(Object instance, int objectId) { + makeInstanceStrong(instance, objectId); + return getUsedMemory(); + } + @RuntimeCallable private void makeInstanceStrong(Object instance, int objectId) { if (instance == null) { From fd129ff71be8fc5c16797ffece00a1da454df6ae Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 09:51:22 +0500 Subject: [PATCH 09/16] fix(android): only an instance of the class JS is constructing takes the reserved object id --- .../jsi/callbackhandlers/CallbackHandlers.cpp | 47 +++++++++++++++++-- .../jsi/callbackhandlers/CallbackHandlers.h | 18 ++----- .../callbackhandlers/CallbackHandlers.cpp | 47 +++++++++++++++++-- .../napi/callbackhandlers/CallbackHandlers.h | 18 ++----- .../src/main/java/com/tns/Runtime.java | 4 +- 5 files changed, 95 insertions(+), 39 deletions(-) diff --git a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp index aad2f5a3..c3e71bf0 100644 --- a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp @@ -112,6 +112,9 @@ void CallbackHandlers::Init(JsRuntime &rt) { CURRENT_OBJECTID_FIELD_ID = jEnv.GetFieldID(RUNTIME_CLASS, "currentObjectId", "I"); assert(CURRENT_OBJECTID_FIELD_ID != nullptr); + CURRENT_OBJECTCLASS_FIELD_ID = jEnv.GetFieldID(RUNTIME_CLASS, "currentObjectClass", "Ljava/lang/Class;"); + assert(CURRENT_OBJECTCLASS_FIELD_ID != nullptr); + REGISTER_CONSTRUCTED_INSTANCE_ID = jEnv.GetMethodID(RUNTIME_CLASS, "registerConstructedInstance", "(Ljava/lang/Object;I)J"); assert(REGISTER_CONSTRUCTED_INSTANCE_ID != nullptr); @@ -536,6 +539,44 @@ JsValue CallbackHandlers::CallJavaMethod(JsRuntime &rt, const JsValue &caller, c } +class CallbackHandlers::ConstructionScope { +public: + struct Construction { + int id; + jclass clazz; + }; + + ConstructionScope(jobject javaRuntime, int javaObjectId, jclass clazz) + : _javaRuntime(javaRuntime), _previous(s_current) { + Publish({javaObjectId, clazz}); + } + + ~ConstructionScope() { + Publish(_previous); + } + + ConstructionScope(const ConstructionScope &) = delete; + + ConstructionScope &operator=(const ConstructionScope &) = delete; + +private: + void Publish(const Construction &construction) { + s_current = construction; + JNIEnv *env = JEnv(); + if (construction.id != -1) { + env->SetObjectField(_javaRuntime, CURRENT_OBJECTCLASS_FIELD_ID, construction.clazz); + } + env->SetIntField(_javaRuntime, CURRENT_OBJECTID_FIELD_ID, construction.id); + } + + static thread_local Construction s_current; + + jobject _javaRuntime; + Construction _previous; +}; + +thread_local CallbackHandlers::ConstructionScope::Construction CallbackHandlers::ConstructionScope::s_current = {-1, nullptr}; + bool CallbackHandlers::RegisterInstance(JsRuntime &rt, const JsValue &jsObject, const std::string &fullClassName, const ArgsWrapper &argWrapper, @@ -565,12 +606,9 @@ bool CallbackHandlers::RegisterInstance(JsRuntime &rt, const JsValue &jsObject, const auto &mi = MethodCache::ResolveConstructorSignature(rt, argWrapper, fullClassName, generatedJavaClass, isInterface); - // while the "instance" is being created, if an exception is thrown during the construction - // this scope will guarantee the "javaObjectID" will be set to -1 and won't have an invalid value jobject instance; { - JavaObjectIdScope objIdScope(jEnv, CURRENT_OBJECTID_FIELD_ID, runtime->GetJavaRuntime(), - javaObjectID); + ConstructionScope construction(runtime->GetJavaRuntime(), javaObjectID, generatedJavaClass); if (argWrapper.type == ArgType::Interface) { instance = jEnv.NewObject(generatedJavaClass, mi.mid); @@ -1806,6 +1844,7 @@ short CallbackHandlers::MAX_JAVA_STRING_ARRAY_LENGTH = 100; jclass CallbackHandlers::RUNTIME_CLASS = nullptr; jclass CallbackHandlers::JAVA_LANG_STRING = nullptr; jfieldID CallbackHandlers::CURRENT_OBJECTID_FIELD_ID = nullptr; +jfieldID CallbackHandlers::CURRENT_OBJECTCLASS_FIELD_ID = nullptr; jmethodID CallbackHandlers::RESOLVE_CLASS_METHOD_ID = nullptr; jmethodID CallbackHandlers::REGISTER_CONSTRUCTED_INSTANCE_ID = nullptr; jmethodID CallbackHandlers::GET_TYPE_METADATA = nullptr; diff --git a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h index 97ad6de7..7b11c360 100644 --- a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h +++ b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h @@ -251,6 +251,8 @@ namespace tns { static jfieldID CURRENT_OBJECTID_FIELD_ID; + static jfieldID CURRENT_OBJECTCLASS_FIELD_ID; + static jmethodID REGISTER_CONSTRUCTED_INSTANCE_ID; static jmethodID GET_TYPE_METADATA; @@ -265,21 +267,7 @@ namespace tns { static FieldAccessor fieldAccessor; - struct JavaObjectIdScope { - JavaObjectIdScope(JEnv &_jEnv, jfieldID fieldId, jobject runtime, int javaObjectId) - : jEnv(_jEnv), _fieldID(fieldId), _runtime(runtime) { - jEnv.SetIntField(_runtime, _fieldID, javaObjectId); - } - - ~JavaObjectIdScope() { - jEnv.SetIntField(_runtime, _fieldID, -1); - } - - private: - JEnv jEnv; - jfieldID _fieldID; - jobject _runtime; - }; + class ConstructionScope; static std::atomic_int64_t count_; diff --git a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp index 003173d4..20c34121 100644 --- a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp @@ -98,6 +98,9 @@ void CallbackHandlers::Init(napi_env env) { CURRENT_OBJECTID_FIELD_ID = jEnv.GetFieldID(RUNTIME_CLASS, "currentObjectId", "I"); assert(CURRENT_OBJECTID_FIELD_ID != nullptr); + CURRENT_OBJECTCLASS_FIELD_ID = jEnv.GetFieldID(RUNTIME_CLASS, "currentObjectClass", "Ljava/lang/Class;"); + assert(CURRENT_OBJECTCLASS_FIELD_ID != nullptr); + REGISTER_CONSTRUCTED_INSTANCE_ID = jEnv.GetMethodID(RUNTIME_CLASS, "registerConstructedInstance", "(Ljava/lang/Object;I)J"); assert(REGISTER_CONSTRUCTED_INSTANCE_ID != nullptr); @@ -547,6 +550,44 @@ napi_value CallbackHandlers::CallJavaMethod(napi_env env, napi_value caller, con } +class CallbackHandlers::ConstructionScope { +public: + struct Construction { + int id; + jclass clazz; + }; + + ConstructionScope(jobject javaRuntime, int javaObjectId, jclass clazz) + : _javaRuntime(javaRuntime), _previous(s_current) { + Publish({javaObjectId, clazz}); + } + + ~ConstructionScope() { + Publish(_previous); + } + + ConstructionScope(const ConstructionScope &) = delete; + + ConstructionScope &operator=(const ConstructionScope &) = delete; + +private: + void Publish(const Construction &construction) { + s_current = construction; + JNIEnv *env = JEnv(); + if (construction.id != -1) { + env->SetObjectField(_javaRuntime, CURRENT_OBJECTCLASS_FIELD_ID, construction.clazz); + } + env->SetIntField(_javaRuntime, CURRENT_OBJECTID_FIELD_ID, construction.id); + } + + static thread_local Construction s_current; + + jobject _javaRuntime; + Construction _previous; +}; + +thread_local CallbackHandlers::ConstructionScope::Construction CallbackHandlers::ConstructionScope::s_current = {-1, nullptr}; + bool CallbackHandlers::RegisterInstance(napi_env env, napi_value jsObject, const std::string &fullClassName, const ArgsWrapper &argWrapper, @@ -576,12 +617,9 @@ bool CallbackHandlers::RegisterInstance(napi_env env, napi_value jsObject, const auto &mi = MethodCache::ResolveConstructorSignature(env, argWrapper, fullClassName, generatedJavaClass, isInterface); - // while the "instance" is being created, if an exception is thrown during the construction - // this scope will guarantee the "javaObjectID" will be set to -1 and won't have an invalid value jobject instance; { - JavaObjectIdScope objIdScope(jEnv, CURRENT_OBJECTID_FIELD_ID, runtime->GetJavaRuntime(), - javaObjectID); + ConstructionScope construction(runtime->GetJavaRuntime(), javaObjectID, generatedJavaClass); if (argWrapper.type == ArgType::Interface) { instance = jEnv.NewObject(generatedJavaClass, mi.mid); @@ -1904,6 +1942,7 @@ short CallbackHandlers::MAX_JAVA_STRING_ARRAY_LENGTH = 100; jclass CallbackHandlers::RUNTIME_CLASS = nullptr; jclass CallbackHandlers::JAVA_LANG_STRING = nullptr; jfieldID CallbackHandlers::CURRENT_OBJECTID_FIELD_ID = nullptr; +jfieldID CallbackHandlers::CURRENT_OBJECTCLASS_FIELD_ID = nullptr; jmethodID CallbackHandlers::RESOLVE_CLASS_METHOD_ID = nullptr; jmethodID CallbackHandlers::REGISTER_CONSTRUCTED_INSTANCE_ID = nullptr; jmethodID CallbackHandlers::GET_TYPE_METADATA = nullptr; diff --git a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h index 66402073..13b597ea 100644 --- a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h +++ b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h @@ -229,6 +229,8 @@ namespace tns { static jfieldID CURRENT_OBJECTID_FIELD_ID; + static jfieldID CURRENT_OBJECTCLASS_FIELD_ID; + static jmethodID REGISTER_CONSTRUCTED_INSTANCE_ID; static jmethodID GET_TYPE_METADATA; @@ -243,21 +245,7 @@ namespace tns { static FieldAccessor fieldAccessor; - struct JavaObjectIdScope { - JavaObjectIdScope(JEnv &_jEnv, jfieldID fieldId, jobject runtime, int javaObjectId) - : jEnv(_jEnv), _fieldID(fieldId), _runtime(runtime) { - jEnv.SetIntField(_runtime, _fieldID, javaObjectId); - } - - ~JavaObjectIdScope() { - jEnv.SetIntField(_runtime, _fieldID, -1); - } - - private: - JEnv jEnv; - jfieldID _fieldID; - jobject _runtime; - }; + class ConstructionScope; static std::atomic_int64_t count_; diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java index 89be95c6..4ca533d8 100644 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -169,6 +169,7 @@ public int newId() { private final java.lang.Runtime dalvikRuntime = java.lang.Runtime.getRuntime(); private int currentObjectId = -1; + private Class currentObjectClass; private ExtractPolicy extractPolicy; @@ -817,7 +818,8 @@ public static void initInstance(Object instance) { int objectId = runtime.currentObjectId; - if (objectId != -1) { + if (objectId != -1 && instance.getClass() == runtime.currentObjectClass) { + runtime.currentObjectId = -1; runtime.makeInstanceStrong(instance, objectId); } else { runtime.createJSInstance(instance); From 0a675e26a7a36bf70cc0471a591049d8766155ce Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 09:54:11 +0500 Subject: [PATCH 10/16] perf(android): pass the method name id so native keeps each name once per runtime --- .../jsi/callbackhandlers/CallbackHandlers.cpp | 16 ++-- .../jsi/callbackhandlers/CallbackHandlers.h | 2 +- .../callbackhandlers/CallbackHandlers.cpp | 14 ++-- .../napi/callbackhandlers/CallbackHandlers.h | 2 +- NativeScript/runtime/android/jsi/Runtime.cpp | 22 +++++- NativeScript/runtime/android/jsi/Runtime.h | 26 +++++-- .../runtime/android/jsi/com_tns_Runtime.cpp | 4 +- NativeScript/runtime/android/napi/Runtime.cpp | 23 +++++- NativeScript/runtime/android/napi/Runtime.h | 33 ++++++-- .../runtime/android/napi/com_tns_Runtime.cpp | 4 +- .../src/main/java/com/tns/MethodNameIds.java | 78 +++++++++++++++++++ .../src/main/java/com/tns/Runtime.java | 6 +- .../test/java/com/tns/MethodNameIdsTest.java | 77 ++++++++++++++++++ 13 files changed, 259 insertions(+), 48 deletions(-) create mode 100644 platforms/android/test-app/runtime/src/main/java/com/tns/MethodNameIds.java create mode 100644 platforms/android/test-app/runtime/src/test/java/com/tns/MethodNameIdsTest.java diff --git a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp index c3e71bf0..c9ca22ac 100644 --- a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp @@ -1171,26 +1171,26 @@ vector CallbackHandlers::GetTypeMetadata(const string &name, int index) JsValue CallbackHandlers::CallJSMethod(JsRuntime &rt, JNIEnv *_jEnv, const JsValue &jsObject, jclass claz, - const string &methodName, int javaObjectId, + const JSMethodCache::MethodName &methodName, int javaObjectId, const JavaCallArgs &args) { JEnv jEnv(_jEnv); auto runtime = Runtime::GetRuntime(rt); - JsValue method = runtime->js_method_cache->getCachedMethod(javaObjectId, methodName); + JsValue method = runtime->js_method_cache->getCachedMethod(javaObjectId, methodName.id); if (method.isUndefined()) { - method = jsObject.asObjectBorrowed(rt).getProperty(rt, methodName); + method = jsObject.asObjectBorrowed(rt).getProperty(rt, methodName.value); if (method.isObject() && method.asObjectBorrowed(rt).isFunction(rt)) { - runtime->js_method_cache->cacheMethod(javaObjectId, methodName, method); + runtime->js_method_cache->cacheMethod(javaObjectId, methodName.id, method); } } if (!method.isObject() || !method.asObjectBorrowed(rt).isFunction(rt)) { stringstream ss; - ss << "Cannot find method '" << methodName << "' implementation"; + ss << "Cannot find method '" << methodName.name << "' implementation"; throw NativeScriptException(ss.str()); } - DEBUG_WRITE("Calling JS Method %s", methodName.c_str()); + DEBUG_WRITE("Calling JS Method %s", methodName.name.c_str()); auto fn = method.asObjectBorrowed(rt).asFunction(rt); auto receiver = jsObject.asObjectBorrowed(rt); @@ -1217,9 +1217,9 @@ JsValue CallbackHandlers::CallJSMethod(JsRuntime &rt, JNIEnv *_jEnv, return fn.callWithThis(rt, receiver); } catch (JsError &e) { if (e.value() != nullptr) { - throw NativeScriptException(rt, *e.value(), "Error calling js method: " + methodName); + throw NativeScriptException(rt, *e.value(), "Error calling js method: " + methodName.name); } - throw NativeScriptException("Error calling js method: " + methodName + ": " + e.what()); + throw NativeScriptException("Error calling js method: " + methodName.name + ": " + e.what()); } } diff --git a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h index 7b11c360..c74436bd 100644 --- a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h +++ b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.h @@ -68,7 +68,7 @@ namespace tns { static JsValue CallJSMethod(JsRuntime &rt, JNIEnv *jEnv, const JsValue &jsObject, jclass claz, - const std::string &methodName, int javaObjectId, const JavaCallArgs &args); + const JSMethodCache::MethodName &methodName, int javaObjectId, const JavaCallArgs &args); static JsValue GetJavaField(JsRuntime &rt, const JsValue &caller, diff --git a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp index 20c34121..c63ea81d 100644 --- a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp @@ -1211,7 +1211,7 @@ vector CallbackHandlers::GetTypeMetadata(const string &name, int index) } napi_value CallbackHandlers::CallJSMethod(napi_env env, JNIEnv *_jEnv, - napi_value jsObject, jclass claz,const string &methodName,int javaObjectId, + napi_value jsObject, jclass claz, const JSMethodCache::MethodName &methodName, int javaObjectId, const JavaCallArgs &args) { JEnv jEnv(_jEnv); napi_status status; @@ -1220,23 +1220,23 @@ napi_value CallbackHandlers::CallJSMethod(napi_env env, JNIEnv *_jEnv, #ifndef __HERMES__ auto runtime = Runtime::GetRuntime(env); - method = runtime->js_method_cache->getCachedMethod(javaObjectId, methodName); + method = runtime->js_method_cache->getCachedMethod(javaObjectId, methodName.id); if (!method) { #endif - NAPI_GUARD(napi_get_named_property(env, jsObject, methodName.c_str(), &method)) {} + NAPI_GUARD(napi_get_property(env, jsObject, napi_util::get_ref_value(env, methodName.value), &method)) {} #ifndef __HERMES__ if (napi_util::is_of_type(env, method, napi_function)) { - runtime->js_method_cache->cacheMethod(javaObjectId, methodName, method); + runtime->js_method_cache->cacheMethod(javaObjectId, methodName.id, method); } } #endif if (method == nullptr || !napi_util::is_of_type(env, method, napi_function)) { stringstream ss; - ss << "Cannot find method '" << methodName << "' implementation"; + ss << "Cannot find method '" << methodName.name << "' implementation"; throw NativeScriptException(ss.str()); } else { - DEBUG_WRITE("Calling JS Method %s", methodName.c_str()); + DEBUG_WRITE("Calling JS Method %s", methodName.name.c_str()); bool exceptionPending; NAPI_GUARD(napi_is_exception_pending(env, &exceptionPending)) {} @@ -1273,7 +1273,7 @@ napi_value CallbackHandlers::CallJSMethod(napi_env env, JNIEnv *_jEnv, if (exceptionPending) { napi_value error; NAPI_GUARD(napi_get_and_clear_last_exception(env, &error)) {} - throw NativeScriptException(env, error, "Error calling js method: " + methodName); + throw NativeScriptException(env, error, "Error calling js method: " + methodName.name); } } } diff --git a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h index 13b597ea..e17f6bd3 100644 --- a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h +++ b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.h @@ -64,7 +64,7 @@ namespace tns { static napi_value CallJSMethod(napi_env env, JNIEnv *jEnv, napi_value jsObject,jclass claz, - const std::string &methodName,int javaObjectId, const JavaCallArgs &args); + const JSMethodCache::MethodName &methodName, int javaObjectId, const JavaCallArgs &args); static napi_value GetJavaField(napi_env env, napi_value caller, FieldCallbackData *fieldData, ObjectManager *objectManager = nullptr, diff --git a/NativeScript/runtime/android/jsi/Runtime.cpp b/NativeScript/runtime/android/jsi/Runtime.cpp index 702157a0..8c93ddac 100644 --- a/NativeScript/runtime/android/jsi/Runtime.cpp +++ b/NativeScript/runtime/android/jsi/Runtime.cpp @@ -713,9 +713,23 @@ int Runtime::GetReader() { return m_mainLooper_fd[0]; } +const JSMethodCache::MethodName &JSMethodCache::getMethodName(jstring javaName, int id) { + if (static_cast(id) >= methodNames.size()) { + methodNames.resize(id + 1); + } + auto &entry = methodNames[id]; + if (entry == nullptr) { + entry = std::make_unique(); + entry->id = id; + entry->name = ArgConverter::jstringToString(javaName); + entry->value = engine::Value(rt->GetJSRuntime(), ArgConverter::convertToJsString(rt->GetJSRuntime(), entry->name)); + } + return *entry; +} + jobject Runtime::CallJSMethodNative(JNIEnv *_jEnv, jobject obj, jint javaObjectID, jclass claz, - jstring methodName, + jstring methodName, jint methodNameId, jint retType, jboolean isConstructor, const JavaCallArgs &args) { JEnv jEnv(_jEnv); engine::Runtime &rt = engineHost->GetRuntime(); @@ -737,11 +751,11 @@ Runtime::CallJSMethodNative(JNIEnv *_jEnv, jobject obj, jint javaObjectID, jclas m_objectManager->SetJavaClass(jsObject, instanceClass); } - string method_name = ArgConverter::jstringToString(methodName); + auto &method = js_method_cache->getMethodName(methodName, methodNameId); - DEBUG_WRITE("CallJSMethodNative called jsObject %s", method_name.c_str()); + DEBUG_WRITE("CallJSMethodNative called jsObject %s", method.name.c_str()); - auto jsResult = CallbackHandlers::CallJSMethod(rt, jEnv, jsObject, claz, method_name, + auto jsResult = CallbackHandlers::CallJSMethod(rt, jEnv, jsObject, claz, method, javaObjectID, args); if (jsResult.isUndefined() || jsResult.isNull()) return nullptr; diff --git a/NativeScript/runtime/android/jsi/Runtime.h b/NativeScript/runtime/android/jsi/Runtime.h index 39a64fff..2760135b 100644 --- a/NativeScript/runtime/android/jsi/Runtime.h +++ b/NativeScript/runtime/android/jsi/Runtime.h @@ -166,8 +166,8 @@ namespace tns { jstring className); jobject CallJSMethodNative(JNIEnv *_env, jobject obj, jint javaObjectID, jclass claz, - jstring methodName, jint retType, jboolean isConstructor, - const JavaCallArgs &args); + jstring methodName, jint methodNameId, jint retType, + jboolean isConstructor, const JavaCallArgs &args); void PassExceptionToJsNative(JNIEnv *env, jobject obj, jthrowable exception, jstring message, @@ -259,8 +259,16 @@ namespace tns { class JSMethodCache { public: + struct MethodName { + int id = -1; + std::string name; + engine::Value value; + }; + explicit JSMethodCache(Runtime *_rt) : rt(_rt) {} + const MethodName &getMethodName(jstring javaName, int id); + ~JSMethodCache() { cleanupCache(); } @@ -268,19 +276,18 @@ namespace tns { // An owned engine::Value is what a napi_ref was here: a handle that // survives handle scopes. There is no refcount to manage, so the cache // stores the value directly and drops it by erasing the entry. - void cacheMethod(int javaObjectId, const std::string &methodName, - const engine::Value &jsMethod) { - methodCache[javaObjectId][methodName] = + void cacheMethod(int javaObjectId, int methodNameId, const engine::Value &jsMethod) { + methodCache[javaObjectId][methodNameId] = engine::Value(rt->GetJSRuntime(), jsMethod); } - engine::Value getCachedMethod(int javaObjectId, const std::string &methodName) { + engine::Value getCachedMethod(int javaObjectId, int methodNameId) { auto it = methodCache.find(javaObjectId); if (it == methodCache.end()) { return engine::Value::undefined(); } - auto methodIt = it->second.find(methodName); + auto methodIt = it->second.find(methodNameId); if (methodIt != it->second.end()) { if (methodIt->second.isUndefined() || methodIt->second.isNull()) { it->second.erase(methodIt->first); @@ -301,12 +308,15 @@ namespace tns { void cleanupCache() { methodCache.clear(); + methodNames.clear(); } private: Runtime *rt; - robin_hood::unordered_map> methodCache; + robin_hood::unordered_map> methodCache; + + std::vector> methodNames; }; diff --git a/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp b/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp index 29e12b0f..7433117e 100644 --- a/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp +++ b/NativeScript/runtime/android/jsi/com_tns_Runtime.cpp @@ -200,7 +200,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_runScript(JNIEnv* _env, jobjec #endif -extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName,jint retType, jboolean isConstructor, jint argCount, jlongArray argValues, jobjectArray argRefs) { +extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName, jint methodNameId, jint retType, jboolean isConstructor, jint argCount, jlongArray argValues, jobjectArray argRefs) { JEnv::EntryScope envScope(_env); jobject result = nullptr; auto runtime = TryGetRuntime(runtimeId); @@ -208,7 +208,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en JSScope scope(runtime->GetEngineHost()); try { - result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, retType, isConstructor, JavaCallArgs{argCount, argValues, argRefs}); + result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, methodNameId, retType, isConstructor, JavaCallArgs{argCount, argValues, argRefs}); } catch (NativeScriptException& e) { e.ReThrowToJava(&runtime->GetJSRuntime()); } catch (std::exception e) { diff --git a/NativeScript/runtime/android/napi/Runtime.cpp b/NativeScript/runtime/android/napi/Runtime.cpp index 51c43038..2afac71a 100644 --- a/NativeScript/runtime/android/napi/Runtime.cpp +++ b/NativeScript/runtime/android/napi/Runtime.cpp @@ -662,9 +662,24 @@ int Runtime::GetReader() { return m_mainLooper_fd[0]; } +const JSMethodCache::MethodName &JSMethodCache::getMethodName(jstring javaName, int id) { + if (static_cast(id) >= methodNames.size()) { + methodNames.resize(id + 1); + } + auto &entry = methodNames[id]; + if (entry == nullptr) { + entry = std::make_unique(); + entry->id = id; + entry->name = ArgConverter::jstringToString(javaName); + auto env = rt->GetNapiEnv(); + entry->value = napi_util::make_ref(env, ArgConverter::convertToJsString(env, entry->name), 1); + } + return *entry; +} + jobject Runtime::CallJSMethodNative(JNIEnv *_jEnv, jobject obj, jint javaObjectID, jclass claz, jstring methodName, - jint retType, jboolean isConstructor, const JavaCallArgs &args) { + jint methodNameId, jint retType, jboolean isConstructor, const JavaCallArgs &args) { JEnv jEnv(_jEnv); DEBUG_WRITE("CallJSMethodNative called javaObjectID=%d", javaObjectID); @@ -678,11 +693,11 @@ Runtime::CallJSMethodNative(JNIEnv *_jEnv, jobject obj, jint javaObjectID, jclas throw NativeScriptException(ss.str()); } - string method_name = ArgConverter::jstringToString(methodName); + auto &method = js_method_cache->getMethodName(methodName, methodNameId); - DEBUG_WRITE("CallJSMethodNative called jsObject %s", method_name.c_str()); + DEBUG_WRITE("CallJSMethodNative called jsObject %s", method.name.c_str()); - auto jsResult = CallbackHandlers::CallJSMethod(env, jEnv, jsObject, claz,method_name, javaObjectID, args); + auto jsResult = CallbackHandlers::CallJSMethod(env, jEnv, jsObject, claz, method, javaObjectID, args); if (napi_util::is_null_or_undefined(env, jsResult)) return nullptr; diff --git a/NativeScript/runtime/android/napi/Runtime.h b/NativeScript/runtime/android/napi/Runtime.h index 87ed3caa..ac91c1ce 100644 --- a/NativeScript/runtime/android/napi/Runtime.h +++ b/NativeScript/runtime/android/napi/Runtime.h @@ -138,8 +138,8 @@ namespace tns { jstring className); jobject CallJSMethodNative(JNIEnv *_env, jobject obj, jint javaObjectID, jclass claz, - jstring methodName, jint retType, jboolean isConstructor, - const JavaCallArgs &args); + jstring methodName, jint methodNameId, jint retType, + jboolean isConstructor, const JavaCallArgs &args); void PassExceptionToJsNative(JNIEnv *env, jobject obj, jthrowable exception, jstring message, @@ -234,18 +234,26 @@ namespace tns { class JSMethodCache { public: + struct MethodName { + int id = -1; + std::string name; + napi_ref value = nullptr; + }; + explicit JSMethodCache(Runtime *_rt) : rt(_rt) {} + const MethodName &getMethodName(jstring javaName, int id); + ~JSMethodCache() { cleanupCache(); } - void cacheMethod(int javaObjectId, const std::string &methodName, napi_value jsMethod) { - methodCache[javaObjectId][methodName] = napi_util::make_ref(rt->GetNapiEnv(), jsMethod, - 0); + void cacheMethod(int javaObjectId, int methodNameId, napi_value jsMethod) { + methodCache[javaObjectId][methodNameId] = napi_util::make_ref(rt->GetNapiEnv(), jsMethod, + 0); } - napi_value getCachedMethod(int javaObjectId, const std::string &methodName) { + napi_value getCachedMethod(int javaObjectId, int methodNameId) { napi_env env = rt->GetNapiEnv(); auto it = methodCache.find(javaObjectId); @@ -253,7 +261,7 @@ namespace tns { return nullptr; } - auto methodIt = it->second.find(methodName); + auto methodIt = it->second.find(methodNameId); if (methodIt != it->second.end()) { if (!methodIt->second) return nullptr; napi_value m = napi_util::get_ref_value(env, methodIt->second); @@ -289,12 +297,21 @@ namespace tns { } } methodCache.clear(); + + for (const auto &methodName: methodNames) { + if (methodName != nullptr && methodName->value != nullptr) { + napi_delete_reference(rt->GetNapiEnv(), methodName->value); + } + } + methodNames.clear(); } private: Runtime *rt; - robin_hood::unordered_map> methodCache; + robin_hood::unordered_map> methodCache; + + std::vector> methodNames; }; diff --git a/NativeScript/runtime/android/napi/com_tns_Runtime.cpp b/NativeScript/runtime/android/napi/com_tns_Runtime.cpp index cd94f070..fae2d22d 100644 --- a/NativeScript/runtime/android/napi/com_tns_Runtime.cpp +++ b/NativeScript/runtime/android/napi/com_tns_Runtime.cpp @@ -180,7 +180,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_runScript(JNIEnv* _env, jobjec return result; } -extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName,jint retType, jboolean isConstructor, jint argCount, jlongArray argValues, jobjectArray argRefs) { +extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jclass claz, jstring methodName, jint methodNameId, jint retType, jboolean isConstructor, jint argCount, jlongArray argValues, jobjectArray argRefs) { JEnv::EntryScope envScope(_env); jobject result = nullptr; auto runtime = TryGetRuntime(runtimeId); @@ -188,7 +188,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en NapiScope scope(runtime->GetNapiEnv()); try { - result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, retType, isConstructor, JavaCallArgs{argCount, argValues, argRefs}); + result = runtime->CallJSMethodNative(_env, obj, javaObjectID, claz, methodName, methodNameId, retType, isConstructor, JavaCallArgs{argCount, argValues, argRefs}); } catch (NativeScriptException& e) { e.ReThrowToJava( runtime->GetNapiEnv()); } catch (std::exception e) { diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/MethodNameIds.java b/platforms/android/test-app/runtime/src/main/java/com/tns/MethodNameIds.java new file mode 100644 index 00000000..2da999ff --- /dev/null +++ b/platforms/android/test-app/runtime/src/main/java/com/tns/MethodNameIds.java @@ -0,0 +1,78 @@ +package com.tns; + +final class MethodNameIds { + private static final class Entry { + final String name; + final int id; + + Entry(String name, int id) { + this.name = name; + this.id = id; + } + } + + private static volatile Entry[] table = new Entry[256]; + private static int count; + + private MethodNameIds() { + } + + static int idOf(String name) { + if (name == null) { + return -1; + } + Entry[] t = table; + int mask = t.length - 1; + for (int i = slot(name, mask); ; i = (i + 1) & mask) { + Entry e = t[i]; + if (e == null) { + return register(name); + } + if (e.name == name || e.name.equals(name)) { + return e.id; + } + } + } + + private static synchronized int register(String name) { + Entry[] t = table; + int mask = t.length - 1; + int i = slot(name, mask); + for (Entry e; (e = t[i]) != null; i = (i + 1) & mask) { + if (e.name.equals(name)) { + return e.id; + } + } + int id = count++; + if (count * 2 > t.length) { + t = grow(t); + mask = t.length - 1; + for (i = slot(name, mask); t[i] != null; i = (i + 1) & mask) { + } + } + t[i] = new Entry(name, id); + table = t; + return id; + } + + private static Entry[] grow(Entry[] old) { + Entry[] t = new Entry[old.length * 2]; + int mask = t.length - 1; + for (Entry e : old) { + if (e == null) { + continue; + } + int i = slot(e.name, mask); + while (t[i] != null) { + i = (i + 1) & mask; + } + t[i] = e; + } + return t; + } + + private static int slot(String name, int mask) { + int h = name.hashCode(); + return (h ^ (h >>> 16)) & mask; + } +} diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java index 4ca533d8..5706ae6d 100644 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -58,7 +58,7 @@ private native void attachNativeScript(int runtimeId, String metadataPath, long private native Object runScript(int runtimeId, String filePath) throws NativeScriptException; - private native Object callJSMethodNative(int runtimeId, int javaObjectID, Class claz, String methodName, int retType, boolean isConstructor, int argCount, long[] argValues, Object[] argRefs) throws NativeScriptException; + private native Object callJSMethodNative(int runtimeId, int javaObjectID, Class claz, String methodName, int methodNameId, int retType, boolean isConstructor, int argCount, long[] argValues, Object[] argRefs) throws NativeScriptException; private native void createJSInstanceNative(int runtimeId, Object javaObject, int javaObjectID, String canonicalName); @@ -1279,7 +1279,7 @@ private Object dispatchCallJSMethodNative(final int javaObjectID, Class claz, if (enableMultithreadedJavascript || isWorkThread) { PackagedArgs packagedArgs = packageArgs(tmpArgs); try { - ret = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, returnType, isConstructor, packagedArgs.count, packagedArgs.values, packagedArgs.refs); + ret = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, MethodNameIds.idOf(methodName), returnType, isConstructor, packagedArgs.count, packagedArgs.values, packagedArgs.refs); } catch (NativeScriptException e) { if (discardUncaughtJsExceptions) { String errorMessage = "Error on \"" + Thread.currentThread().getName() + "\" thread for callJSMethodNative\n"; @@ -1300,7 +1300,7 @@ public void run() { synchronized (this) { try { final PackagedArgs packagedArgs = packageArgs(tmpArgs); - arr[0] = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, returnType, isCtor, packagedArgs.count, packagedArgs.values, packagedArgs.refs); + arr[0] = callJSMethodNative(getRuntimeId(), javaObjectID, claz, methodName, MethodNameIds.idOf(methodName), returnType, isCtor, packagedArgs.count, packagedArgs.values, packagedArgs.refs); } catch (NativeScriptException e) { if (discardUncaughtJsExceptions) { String errorMessage = "Error on \"" + Thread.currentThread().getName() + "\" thread for callJSMethodNative\n"; diff --git a/platforms/android/test-app/runtime/src/test/java/com/tns/MethodNameIdsTest.java b/platforms/android/test-app/runtime/src/test/java/com/tns/MethodNameIdsTest.java new file mode 100644 index 00000000..ef832fa2 --- /dev/null +++ b/platforms/android/test-app/runtime/src/test/java/com/tns/MethodNameIdsTest.java @@ -0,0 +1,77 @@ +package com.tns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; + +public class MethodNameIdsTest { + @Test + public void givesEqualNamesOneIdAndDistinctNamesDistinctIds() { + int a = MethodNameIds.idOf("testName_a"); + int b = MethodNameIds.idOf("testName_b"); + + assertNotEquals(a, b); + assertEquals(a, MethodNameIds.idOf("testName_a")); + assertEquals(a, MethodNameIds.idOf(new String("testName_a"))); + assertEquals(-1, MethodNameIds.idOf(null)); + } + + @Test + public void keepsIdsAcrossGrowth() { + List ids = new ArrayList<>(); + for (int i = 0; i < 2000; i++) { + ids.add(MethodNameIds.idOf("testGrowth_" + i)); + } + Set distinct = new HashSet<>(ids); + assertEquals(2000, distinct.size()); + for (int i = 0; i < 2000; i++) { + assertEquals((int) ids.get(i), MethodNameIds.idOf("testGrowth_" + i)); + } + } + + @Test + public void agreesAcrossThreadsRegisteringTheSameNames() throws Exception { + final int threads = 8; + final int names = 500; + final ConcurrentHashMap seen = new ConcurrentHashMap<>(); + final List failures = new ArrayList<>(); + final CountDownLatch start = new CountDownLatch(1); + List workers = new ArrayList<>(); + for (int t = 0; t < threads; t++) { + Thread worker = new Thread(() -> { + try { + start.await(); + for (int i = 0; i < names; i++) { + String name = "testRace_" + i; + int id = MethodNameIds.idOf(name); + Integer previous = seen.putIfAbsent(name, id); + if (previous != null && previous != id) { + throw new AssertionError(name + " got " + id + " and " + previous); + } + } + } catch (Throwable e) { + synchronized (failures) { + failures.add(e); + } + } + }); + workers.add(worker); + worker.start(); + } + start.countDown(); + for (Thread worker : workers) { + worker.join(); + } + assertTrue(failures.toString(), failures.isEmpty()); + assertEquals(names, new HashSet<>(seen.values()).size()); + } +} From 3c5b34ec197b7d6a4db52dfb8677dc19d0a923ec Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 09:54:12 +0500 Subject: [PATCH 11/16] perf(android): bind the runtime's own exported functions locally --- platforms/android/test-app/runtime/CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/platforms/android/test-app/runtime/CMakeLists.txt b/platforms/android/test-app/runtime/CMakeLists.txt index d12df14e..17c12185 100644 --- a/platforms/android/test-app/runtime/CMakeLists.txt +++ b/platforms/android/test-app/runtime/CMakeLists.txt @@ -487,6 +487,8 @@ if("${ANDROID_ABI}" MATCHES "arm64-v8a$" OR "${ANDROID_ABI}" MATCHES "x86_64$") target_link_options(NativeScript PRIVATE "-Wl,-z,max-page-size=16384") endif() +target_link_options(NativeScript PRIVATE "-Wl,-Bsymbolic-functions") + # Command info: https://cmake.org/cmake/help/v3.4/command/find_library.html # Searches for a specified prebuilt library and stores the path as a # variable. Because CMake includes system libraries in the search path by From d2ade0b7f6dc707563bda0e9b14264b80c50074a Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 09:57:41 +0500 Subject: [PATCH 12/16] perf(android): send a dense class index with each object so native caches the class once --- .../jsi/callbackhandlers/CallbackHandlers.cpp | 14 ++--- .../ffi/jni/jsi/conversion/ArgConverter.cpp | 8 +-- .../ffi/jni/jsi/conversion/ArrayHelper.cpp | 3 +- .../ffi/jni/jsi/metadata/FieldAccessor.cpp | 9 +-- .../jni/jsi/objectmanager/ObjectManager.cpp | 49 ++++++++++++++++ .../ffi/jni/jsi/objectmanager/ObjectManager.h | 25 ++++++++ .../callbackhandlers/CallbackHandlers.cpp | 12 ++-- .../ffi/jni/napi/conversion/ArgConverter.cpp | 8 +-- .../ffi/jni/napi/conversion/ArrayHelper.cpp | 3 +- .../ffi/jni/napi/metadata/FieldAccessor.cpp | 10 +--- .../jni/napi/objectmanager/ObjectManager.cpp | 49 ++++++++++++++++ .../jni/napi/objectmanager/ObjectManager.h | 25 ++++++++ .../src/main/java/com/tns/Runtime.java | 57 ++++++++++++------- 13 files changed, 202 insertions(+), 70 deletions(-) diff --git a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp index c9ca22ac..3f4de07f 100644 --- a/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/jsi/callbackhandlers/CallbackHandlers.cpp @@ -516,14 +516,15 @@ JsValue CallbackHandlers::CallJavaMethod(JsRuntime &rt, const JsValue &caller, c if (isString) { returnValue = ArgConverter::jstringToJsString(rt, (jstring) result); } else { - jint javaObjectID = objectManager->GetOrCreateObjectId(result); + jlong packed = objectManager->GetOrCreateObjectIdAndClass(result); + jint javaObjectID = ObjectManager::IdOf(packed); returnValue = objectManager->GetJsObjectByJavaObject(javaObjectID); if (js_util::is_null_or_undefined(returnValue)) { MetadataNode *returnNode = ResolveDeclaredReturnNode(jEnv, entry, result); returnValue = returnNode != nullptr ? objectManager->CreateJSWrapper(javaObjectID, returnNode, entry->returnClass) - : objectManager->CreateJSWrapper(javaObjectID, *returnType, result); + : objectManager->CreateJSWrapper(javaObjectID, ObjectManager::ClassIndexOf(packed), result); } } @@ -1230,14 +1231,7 @@ JsValue CallbackHandlers::FindClass(JsRuntime &rt, const char *name) { auto runtime = Runtime::GetRuntime(rt); auto objectManager = runtime->GetObjectManager(); - jint javaObjectID = objectManager->GetOrCreateObjectId(javaClass); - JsValue clazz = objectManager->GetJsObjectByJavaObject(javaObjectID); - - if (js_util::is_null_or_undefined(clazz)) { - clazz = objectManager->CreateJSWrapper(javaObjectID, "Ljava/lang/Class;", javaClass); - } - - return clazz; + return objectManager->GetOrCreateJSWrapper(javaClass); } return js_util::undefined(); } diff --git a/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp b/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp index 9781597f..247e66bb 100644 --- a/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp +++ b/NativeScript/ffi/jni/jsi/conversion/ArgConverter.cpp @@ -193,14 +193,12 @@ void ArgConverter::ConvertJavaArgsToJsArgs(JsRuntime &rt, const JavaCallArgs &ar break; } case Type::JsObject: { - auto javaObjectID = static_cast(bits); + auto javaObjectID = ObjectManager::IdOf(bits); jsArg = objectManager->GetJsObjectByJavaObject(javaObjectID); if (js_util::is_null_or_undefined(jsArg)) { - JniLocalRef argJavaClassPath(jni->GetObjectArrayElement(args.refs, i)); - string argClassName = jstringToString(ObjectToString(argJavaClassPath)); - argClassName = Util::ConvertFromCanonicalToJniName(argClassName); - jsArg = objectManager->CreateJSWrapper(javaObjectID, argClassName); + JniLocalRef arg(jni->GetObjectArrayElement(args.refs, i)); + jsArg = objectManager->CreateJSWrapper(javaObjectID, ObjectManager::ClassIndexOf(bits), arg); } break; } diff --git a/NativeScript/ffi/jni/jsi/conversion/ArrayHelper.cpp b/NativeScript/ffi/jni/jsi/conversion/ArrayHelper.cpp index 05c632b1..6b93a2c3 100644 --- a/NativeScript/ffi/jni/jsi/conversion/ArrayHelper.cpp +++ b/NativeScript/ffi/jni/jsi/conversion/ArrayHelper.cpp @@ -105,8 +105,7 @@ JsValue ArrayHelper::CreateJavaArray(JsRuntime &rt, const JsValue *args, size_t throw JsError(rt, "Expect primitive type name or class function as a first argument"); } - jint javaObjectID = objectManager->GetOrCreateObjectId(array); - return objectManager->CreateJSWrapper(javaObjectID, "" /* ignored */, array); + return objectManager->GetOrCreateJSWrapper(array); } jobject ArrayHelper::CreateArrayByClassName(const string& typeName, int length) { diff --git a/NativeScript/ffi/jni/jsi/metadata/FieldAccessor.cpp b/NativeScript/ffi/jni/jsi/metadata/FieldAccessor.cpp index 4ddf6011..85d1e45a 100644 --- a/NativeScript/ffi/jni/jsi/metadata/FieldAccessor.cpp +++ b/NativeScript/ffi/jni/jsi/metadata/FieldAccessor.cpp @@ -165,14 +165,7 @@ FieldAccessor::GetJavaField(JsRuntime &rt, const JsValue &target, FieldCallbackD if (isString) { fieldResult = ArgConverter::jstringToJsString(rt, (jstring) result); } else { - int javaObjectID = objectManager->GetOrCreateObjectId(result); - auto objectResult = objectManager->GetJsObjectByJavaObject(javaObjectID); - - if (js_util::is_null_or_undefined(objectResult)) { - objectResult = objectManager->CreateJSWrapper(javaObjectID, fieldTypeName, result); - } - - fieldResult = objectResult; + fieldResult = objectManager->GetOrCreateJSWrapper(result); } jEnv.DeleteLocalRef(result); diff --git a/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.cpp b/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.cpp index c570228e..745885eb 100644 --- a/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.cpp +++ b/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.cpp @@ -39,6 +39,11 @@ ObjectManager::ObjectManager(jobject javaRuntimeObject) : "(Ljava/lang/Object;)I"); assert(GET_OR_CREATE_JAVA_OBJECT_ID_METHOD_ID != nullptr); + GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID = env.GetMethodID(runtimeClass, + "getOrCreateJavaObjectIDAndClass", + "(Ljava/lang/Object;)J"); + assert(GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID != nullptr); + MAKE_INSTANCES_WEAK_METHOD_ID = env.GetMethodID(runtimeClass, "makeInstancesWeak", "([II)V"); assert(MAKE_INSTANCES_WEAK_METHOD_ID != nullptr); @@ -93,6 +98,13 @@ void ObjectManager::OnDisposeRuntime() { // weak reference table is finite. m_cache.clear(); + for (auto &info: m_classInfos) { + if (info.clazz != nullptr) { + jEnv.DeleteGlobalRef(info.clazz); + } + } + m_classInfos.clear(); + // The host-object proxies are owned by the *engine*, and each holds an owned // handle to the instance it wraps. Nothing above reaches them: they are only // destroyed when the engine tears its heap down, at which point @@ -589,6 +601,35 @@ int ObjectManager::GetOrCreateObjectId(jobject object) { return javaObjectID; } +jlong ObjectManager::GetOrCreateObjectIdAndClass(jobject object) { + JEnv env; + return env.CallLongMethod(m_javaRuntimeObject, GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID, + object); +} + +JsValue ObjectManager::GetOrCreateJSWrapper(jobject object) { + jlong packed = GetOrCreateObjectIdAndClass(object); + JsValue wrapper = GetJsObjectByJavaObject(IdOf(packed)); + if (!js_util::is_null_or_undefined(wrapper)) { + return wrapper; + } + return CreateJSWrapper(IdOf(packed), ClassIndexOf(packed), object); +} + +ObjectManager::ClassInfo ObjectManager::ResolveClassInfo(jint classIndex, jobject instance) { + if (static_cast(classIndex) >= m_classInfos.size()) { + m_classInfos.resize(classIndex + 1); + } + ClassInfo &info = m_classInfos[classIndex]; + if (info.node == nullptr) { + JEnv env; + JniLocalRef clazz(env.GetObjectClass(instance)); + info.node = MetadataNode::GetOrCreate(GetClassName((jclass) clazz)); + info.clazz = (jclass) env.NewGlobalRef(clazz); + } + return info; +} + JsValue ObjectManager::GetJsObjectByJavaObject(int javaObjectID) { auto it = m_idToObject.find(javaObjectID); if (it == m_idToObject.end()) { @@ -628,6 +669,14 @@ JsValue ObjectManager::CreateJSWrapper(jint javaObjectID, const std::string &typ return CreateJSWrapperHelper(javaObjectID, typeName, clazz); } +JsValue ObjectManager::CreateJSWrapper(jint javaObjectID, jint classIndex, jobject instance) { + if (classIndex <= 0) { + return CreateJSWrapper(javaObjectID, std::string(), instance); + } + ClassInfo info = ResolveClassInfo(classIndex, instance); + return CreateJSWrapper(javaObjectID, info.node, info.clazz); +} + JsValue ObjectManager::CreateJSWrapperHelper(jint javaObjectID, const std::string &typeName, jclass clazz) { auto className = (clazz != nullptr) ? GetClassName(clazz) : typeName; diff --git a/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.h b/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.h index e8a9e53e..e9ee89bd 100644 --- a/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.h +++ b/NativeScript/ffi/jni/jsi/objectmanager/ObjectManager.h @@ -40,6 +40,20 @@ namespace tns { int GetOrCreateObjectId(jobject object); + jlong GetOrCreateObjectIdAndClass(jobject object); + + static jint IdOf(jlong packed) { + return static_cast(packed); + } + + static jint ClassIndexOf(jlong packed) { + return static_cast((packed >> 32) & 0x7fffffff); + } + + JsValue GetOrCreateJSWrapper(jobject object); + + JsValue CreateJSWrapper(jint javaObjectID, jint classIndex, jobject instance); + JsValue GetJsObjectByJavaObject(int javaObjectID); JsValue CreateJSWrapper(jint javaObjectID, const std::string &typeName); @@ -214,6 +228,13 @@ namespace tns { JsValue CreateJSWrapperHelper(jint javaObjectID, const std::string &typeName, jclass clazz); + struct ClassInfo { + MetadataNode *node = nullptr; + jclass clazz = nullptr; + }; + + ClassInfo ResolveClassInfo(jint classIndex, jobject instance); + void EnsureInstanceStrong(int javaObjectID); void MarkInstanceWeak(int javaObjectID); @@ -255,6 +276,8 @@ namespace tns { robin_hood::unordered_set m_weakObjectIds; robin_hood::unordered_set m_markedAsWeakIds; robin_hood::unordered_set m_pendingWeakIds; + + std::vector m_classInfos; bool m_flushPosted = false; // Every live host-object proxy. The engine owns the proxies, so without @@ -286,6 +309,8 @@ namespace tns { jmethodID GET_OR_CREATE_JAVA_OBJECT_ID_METHOD_ID; + jmethodID GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID; + jmethodID MAKE_INSTANCES_WEAK_METHOD_ID; jmethodID MAKE_INSTANCE_STRONG_METHOD_ID; diff --git a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp index c63ea81d..ce942afa 100644 --- a/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp +++ b/NativeScript/ffi/jni/napi/callbackhandlers/CallbackHandlers.cpp @@ -520,14 +520,15 @@ napi_value CallbackHandlers::CallJavaMethod(napi_env env, napi_value caller, con if (isString) { returnValue = ArgConverter::jstringToJsString(env, (jstring) result); } else { - jint javaObjectID = objectManager->GetOrCreateObjectId(result); + jlong packed = objectManager->GetOrCreateObjectIdAndClass(result); + jint javaObjectID = ObjectManager::IdOf(packed); returnValue = objectManager->GetJsObjectByJavaObject(javaObjectID); if (napi_util::is_null_or_undefined(env, returnValue)) { MetadataNode *returnNode = ResolveDeclaredReturnNode(jEnv, entry, result); returnValue = returnNode != nullptr ? objectManager->CreateJSWrapper(javaObjectID, returnNode, entry->returnClass) - : objectManager->CreateJSWrapper(javaObjectID, *returnType, result); + : objectManager->CreateJSWrapper(javaObjectID, ObjectManager::ClassIndexOf(packed), result); } } @@ -1290,12 +1291,7 @@ napi_value CallbackHandlers::FindClass(napi_env env, const char *name) { auto runtime = Runtime::GetRuntime(env); auto objectManager = runtime->GetObjectManager(); - jint javaObjectID = objectManager->GetOrCreateObjectId(javaClass); - clazz = objectManager->GetJsObjectByJavaObject(javaObjectID); - - if (clazz == nullptr) { - clazz = objectManager->CreateJSWrapper(javaObjectID, "Ljava/lang/Class;", javaClass); - } + clazz = objectManager->GetOrCreateJSWrapper(javaClass); } return clazz; } diff --git a/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp b/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp index 8fa827d0..1a86564d 100644 --- a/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp +++ b/NativeScript/ffi/jni/napi/conversion/ArgConverter.cpp @@ -241,14 +241,12 @@ void ArgConverter::ConvertJavaArgsToJsArgs(napi_env env, const JavaCallArgs &arg break; } case Type::JsObject: { - auto javaObjectID = static_cast(bits); + auto javaObjectID = ObjectManager::IdOf(bits); jsArg = objectManager->GetJsObjectByJavaObject(javaObjectID); if (napi_util::is_null_or_undefined(env, jsArg)) { - JniLocalRef argJavaClassPath(jni->GetObjectArrayElement(args.refs, i)); - string argClassName = jstringToString(ObjectToString(argJavaClassPath)); - argClassName = Util::ConvertFromCanonicalToJniName(argClassName); - jsArg = objectManager->CreateJSWrapper(javaObjectID, argClassName); + JniLocalRef arg(jni->GetObjectArrayElement(args.refs, i)); + jsArg = objectManager->CreateJSWrapper(javaObjectID, ObjectManager::ClassIndexOf(bits), arg); } break; } diff --git a/NativeScript/ffi/jni/napi/conversion/ArrayHelper.cpp b/NativeScript/ffi/jni/napi/conversion/ArrayHelper.cpp index f00b4c57..f061f7fd 100644 --- a/NativeScript/ffi/jni/napi/conversion/ArrayHelper.cpp +++ b/NativeScript/ffi/jni/napi/conversion/ArrayHelper.cpp @@ -148,8 +148,7 @@ napi_value ArrayHelper::CreateJavaArray(napi_env env, napi_callback_info info) { return nullptr; } - jint javaObjectID = objectManager->GetOrCreateObjectId(array); - return objectManager->CreateJSWrapper(javaObjectID, "" /* ignored */, array); + return objectManager->GetOrCreateJSWrapper(array); } void ArrayHelper::Throw(napi_env env, const std::string& errorMessage) { diff --git a/NativeScript/ffi/jni/napi/metadata/FieldAccessor.cpp b/NativeScript/ffi/jni/napi/metadata/FieldAccessor.cpp index bf12961f..696a2e14 100644 --- a/NativeScript/ffi/jni/napi/metadata/FieldAccessor.cpp +++ b/NativeScript/ffi/jni/napi/metadata/FieldAccessor.cpp @@ -182,15 +182,7 @@ FieldAccessor::GetJavaField(napi_env env, napi_value target, FieldCallbackData * if (isString) { fieldResult = ArgConverter::jstringToJsString(env, (jstring) result); } else { - int javaObjectID = objectManager->GetOrCreateObjectId(result); - auto objectResult = objectManager->GetJsObjectByJavaObject(javaObjectID); - - if (napi_util::is_null_or_undefined(env, objectResult)) { - objectResult = objectManager->CreateJSWrapper(javaObjectID, fieldTypeName, - result); - } - - fieldResult = objectResult; + fieldResult = objectManager->GetOrCreateJSWrapper(result); } jEnv.DeleteLocalRef(result); } else { diff --git a/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.cpp b/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.cpp index 1a0dc5a6..f00a8fd1 100644 --- a/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.cpp +++ b/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.cpp @@ -39,6 +39,11 @@ ObjectManager::ObjectManager(jobject javaRuntimeObject) : "(Ljava/lang/Object;)I"); assert(GET_OR_CREATE_JAVA_OBJECT_ID_METHOD_ID != nullptr); + GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID = env.GetMethodID(runtimeClass, + "getOrCreateJavaObjectIDAndClass", + "(Ljava/lang/Object;)J"); + assert(GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID != nullptr); + MAKE_INSTANCES_WEAK_METHOD_ID = env.GetMethodID(runtimeClass, "makeInstancesWeak", "([II)V"); assert(MAKE_INSTANCES_WEAK_METHOD_ID != nullptr); @@ -92,6 +97,13 @@ void ObjectManager::OnDisposeEnv() { // Its destructor leaves the weak global refs alive, and the process-wide // weak reference table is finite. m_cache.clear(); + + for (auto &info: m_classInfos) { + if (info.clazz != nullptr) { + jEnv.DeleteGlobalRef(info.clazz); + } + } + m_classInfos.clear(); } napi_value ObjectManager::GetOrCreateProxyWeak(jint javaObjectID, napi_value instance) { @@ -770,6 +782,35 @@ int ObjectManager::GetOrCreateObjectId(jobject object) { return javaObjectID; } +jlong ObjectManager::GetOrCreateObjectIdAndClass(jobject object) { + JEnv env; + return env.CallLongMethod(m_javaRuntimeObject, GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID, + object); +} + +napi_value ObjectManager::GetOrCreateJSWrapper(jobject object) { + jlong packed = GetOrCreateObjectIdAndClass(object); + napi_value wrapper = GetJsObjectByJavaObject(IdOf(packed)); + if (!napi_util::is_null_or_undefined(m_env, wrapper)) { + return wrapper; + } + return CreateJSWrapper(IdOf(packed), ClassIndexOf(packed), object); +} + +ObjectManager::ClassInfo ObjectManager::ResolveClassInfo(jint classIndex, jobject instance) { + if (static_cast(classIndex) >= m_classInfos.size()) { + m_classInfos.resize(classIndex + 1); + } + ClassInfo &info = m_classInfos[classIndex]; + if (info.node == nullptr) { + JEnv env; + JniLocalRef clazz(env.GetObjectClass(instance)); + info.node = MetadataNode::GetOrCreate(GetClassName((jclass) clazz)); + info.clazz = (jclass) env.NewGlobalRef(clazz); + } + return info; +} + napi_value ObjectManager::GetJsObjectByJavaObject(int javaObjectID) { auto it = m_idToObject.find(javaObjectID); if (it == m_idToObject.end()) { @@ -804,6 +845,14 @@ ObjectManager::CreateJSWrapper(jint javaObjectID, const std::string &typeName, j return CreateJSWrapperHelper(javaObjectID, typeName, clazz); } +napi_value ObjectManager::CreateJSWrapper(jint javaObjectID, jint classIndex, jobject instance) { + if (classIndex <= 0) { + return CreateJSWrapper(javaObjectID, std::string(), instance); + } + ClassInfo info = ResolveClassInfo(classIndex, instance); + return CreateJSWrapper(javaObjectID, info.node, info.clazz); +} + napi_value ObjectManager::CreateJSWrapperHelper(jint javaObjectID, const std::string &typeName, jclass clazz) { auto className = (clazz != nullptr) ? GetClassName(clazz) : typeName; diff --git a/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.h b/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.h index ad8e328f..e34ede6d 100644 --- a/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.h +++ b/NativeScript/ffi/jni/napi/objectmanager/ObjectManager.h @@ -38,6 +38,20 @@ namespace tns { int GetOrCreateObjectId(jobject object); + jlong GetOrCreateObjectIdAndClass(jobject object); + + static jint IdOf(jlong packed) { + return static_cast(packed); + } + + static jint ClassIndexOf(jlong packed) { + return static_cast((packed >> 32) & 0x7fffffff); + } + + napi_value GetOrCreateJSWrapper(jobject object); + + napi_value CreateJSWrapper(jint javaObjectID, jint classIndex, jobject instance); + napi_value GetJsObjectByJavaObject(int javaObjectID); napi_value @@ -174,6 +188,13 @@ namespace tns { static void JSObjectPostFinalizerCallback(napi_env env, void *finalizeData, void *finalizeHint); + struct ClassInfo { + MetadataNode *node = nullptr; + jclass clazz = nullptr; + }; + + ClassInfo ResolveClassInfo(jint classIndex, jobject instance); + void EnsureInstanceStrong(int javaObjectID); void MarkInstanceWeak(int javaObjectID); @@ -204,6 +225,8 @@ namespace tns { robin_hood::unordered_set m_weakObjectIds; robin_hood::unordered_set m_markedAsWeakIds; robin_hood::unordered_set m_pendingWeakIds; + + std::vector m_classInfos; bool m_flushPosted = false; LRUCache m_cache; @@ -222,6 +245,8 @@ namespace tns { jmethodID GET_OR_CREATE_JAVA_OBJECT_ID_METHOD_ID; + jmethodID GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID; + jmethodID MAKE_INSTANCES_WEAK_METHOD_ID; jmethodID MAKE_INSTANCE_STRONG_METHOD_ID; diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java index 5706ae6d..65a60eba 100644 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -158,14 +158,6 @@ public int newId() { private Map, JavaScriptImplementation> loadedJavaScriptExtends = new HashMap, JavaScriptImplementation>(); - // Classes already registered via classStorageService.storeClass, so repeated - // object registrations of the same class (e.g. thousands of java.util.Date - // instances) skip the redundant getClass().getName() string + cache/classloader - // puts. Class uses identity equals/hashCode, so a plain concurrent set is - // correct and thread-safe. - private final java.util.Set> storedClasses = - java.util.Collections.newSetFromMap(new ConcurrentHashMap, Boolean>()); - private final java.lang.Runtime dalvikRuntime = java.lang.Runtime.getRuntime(); private int currentObjectId = -1; @@ -231,6 +223,30 @@ public int compare(Method lhs, Method rhs) { private static final ClassStorageService classStorageService = new ClassStorageServiceImpl(ClassCacheImpl.INSTANCE, ClassLoadersCollectionImpl.INSTANCE); + private static final ConcurrentHashMap, Integer> classIndices = new ConcurrentHashMap<>(); + private static int nextClassIndex = 1; + + static int classIndexOf(Class clazz) { + Integer index = classIndices.get(clazz); + return index != null ? index : registerClass(clazz); + } + + private static int registerClass(Class clazz) { + synchronized (classIndices) { + Integer index = classIndices.get(clazz); + if (index == null) { + classStorageService.storeClass(clazz.getName(), clazz); + index = nextClassIndex++; + classIndices.put(clazz, index); + } + return index; + } + } + + static long packIdAndClass(int objectId, Object obj) { + return ((long) classIndexOf(obj.getClass()) << 32) | (objectId & 0xFFFFFFFFL); + } + public Runtime(ClassResolver classResolver, GcListener gcListener, StaticConfiguration config, DynamicConfiguration dynamicConfig, int runtimeId, int workerId, ObjectTable objectTable) { this.classResolver = classResolver; this.gcListener = gcListener; @@ -983,13 +999,7 @@ private void makeInstanceStrong(Object instance, int objectId) { objectTable.putStrong(objectId, instance); - Class clazz = instance.getClass(); - // Only resolve the name + store the class the first time we see it; the - // storage is keyed by class name and the classloader set is idempotent, so - // repeated registrations of the same class are pure overhead. - if (storedClasses.add(clazz)) { - classStorageService.storeClass(clazz.getName(), clazz); - } + classIndexOf(instance.getClass()); if (logger != null && logger.isEnabled()) { logger.write("MakeInstanceStrong (" + objectId + ", " + instance.getClass().toString() + ")"); @@ -1038,6 +1048,11 @@ private Integer getJavaObjectID(Object obj) { return id == ObjectTable.NO_ID ? null : id; } + @RuntimeCallable + private long getOrCreateJavaObjectIDAndClass(Object obj) { + return packIdAndClass(getOrCreateJavaObjectID(obj), obj); + } + @RuntimeCallable private int getOrCreateJavaObjectID(Object obj) { Integer result = getJavaObjectID(obj); @@ -1155,10 +1170,10 @@ private static final class PackagedArgs { Object[] refs; } - // Packages args as one long[]: count raw values (the bits of a primitive, an object's id), - // then one type id per byte, eight to a slot. A reference is kept only for strings (the - // string) and objects (the canonical class name). A javaObject with no javaObjectID, - // meaning javascript has no object for it yet, is assigned one. + // Packages args as one long[]: count raw values (the bits of a primitive, an object's id + // and class index), then one type id per byte, eight to a slot. A reference is kept only + // for strings and objects. A javaObject with no javaObjectID, meaning javascript has no + // object for it yet, is assigned one. private PackagedArgs packageArgs(Object... args) { PackagedArgs packaged = new PackagedArgs(); if (args == null || args.length == 0) { @@ -1194,8 +1209,8 @@ private PackagedArgs packageArgs(Object... args) { if (packaged.refs == null) { packaged.refs = new Object[len]; } - packaged.refs[i] = value.getClass().getName(); - values[i] = getOrCreateJavaObjectID(value); + packaged.refs[i] = value; + values[i] = packIdAndClass(getOrCreateJavaObjectID(value), value); } } From 3e08da1f0ffa4bc9de9d124d02dae149dc890866 Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 10:00:21 +0500 Subject: [PATCH 13/16] perf(android): tag each binding with its runtime and object id and index runtimes by id --- .../tests/testsForRuntimeBindingGenerator.js | 8 +-- .../staticbindinggenerator/Generator.java | 2 + .../generating/writing/FieldsWriter.java | 1 + .../generating/writing/MethodsWriter.java | 1 + .../writing/impl/ClassWriterImpl.java | 4 ++ .../writing/impl/FieldsWriterImpl.java | 11 +++ .../writing/impl/MethodsWriterImpl.java | 16 +++++ .../com/tns/NativeScriptRuntimeBound.java | 14 ++++ .../test/GeneratorTest.java | 28 +++++++- .../com/tns/NativeScriptRuntimeBound.java | 14 ++++ .../src/main/java/com/tns/bindings/Dump.java | 34 +++++++++- .../src/main/java/com/tns/Runtime.java | 67 +++++++++++++++++-- 12 files changed, 185 insertions(+), 15 deletions(-) create mode 100644 platforms/android/test-app/build-tools/static-binding-generator/src/test/java/com/tns/NativeScriptRuntimeBound.java create mode 100644 platforms/android/test-app/runtime-binding-generator/src/main/java/com/tns/NativeScriptRuntimeBound.java diff --git a/platforms/android/test-app/app/src/main/assets/app/tests/testsForRuntimeBindingGenerator.js b/platforms/android/test-app/app/src/main/assets/app/tests/testsForRuntimeBindingGenerator.js index da3c6033..f902bb91 100644 --- a/platforms/android/test-app/app/src/main/assets/app/tests/testsForRuntimeBindingGenerator.js +++ b/platforms/android/test-app/app/src/main/assets/app/tests/testsForRuntimeBindingGenerator.js @@ -109,9 +109,9 @@ describe("Tests for runtime binding generator", function () { var interfaces = clazz.getInterfaces(); - var expectedInterfaces = ["java.util.jar.Pack200$Packer", "java.util.Formattable", "java.util.Observer", "java.util.jar.Pack200$Unpacker", "com.tns.NativeScriptHashCodeProvider"]; + var expectedInterfaces = ["java.util.jar.Pack200$Packer", "java.util.Formattable", "java.util.Observer", "java.util.jar.Pack200$Unpacker", "com.tns.NativeScriptHashCodeProvider", "com.tns.NativeScriptRuntimeBound"]; - expect(interfaces.length).toBe(5); + expect(interfaces.length).toBe(6); for(var i = 0; i < interfaces.length; i++) { var interfaceName = interfaces[i].getName().toString(); @@ -166,9 +166,9 @@ describe("Tests for runtime binding generator", function () { var interfaces = clazz.getInterfaces(); - var expectedInterfaces = ["java.util.jar.Pack200$Packer", "java.util.Formattable", "java.util.Observer", "java.util.jar.Pack200$Unpacker", "com.tns.NativeScriptHashCodeProvider"]; + var expectedInterfaces = ["java.util.jar.Pack200$Packer", "java.util.Formattable", "java.util.Observer", "java.util.jar.Pack200$Unpacker", "com.tns.NativeScriptHashCodeProvider", "com.tns.NativeScriptRuntimeBound"]; - expect(interfaces.length).toBe(5); + expect(interfaces.length).toBe(6); for(var i = 0; i < interfaces.length; i++) { var interfaceName = interfaces[i].getName().toString(); diff --git a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/Generator.java b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/Generator.java index acdaf6f1..942b6b18 100644 --- a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/Generator.java +++ b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/Generator.java @@ -413,6 +413,7 @@ private void writeFieldsToWriter(Writer writer, JavaClass clazz) { boolean isApplicationClass = androidClassChecker.isApplicationClass(clazz); fieldsWriter.writePublicRuntimeIdField(); + fieldsWriter.writeRuntimeTagField(); if (isApplicationClass) { String normalizedClassName = BcelNamingUtil.resolveClassName(clazz.getClassName()); @@ -493,6 +494,7 @@ private void writeMethodsToWriter(Writer writer, GenericHierarchyView genericHie methodsWriter.writeInternalRuntimeHashCodeMethod(); methodsWriter.writeInternalRuntimeEqualsMethod(); + methodsWriter.writeInternalRuntimeTagAccessorMethods(); } /** diff --git a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/FieldsWriter.java b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/FieldsWriter.java index 9c34561d..39215078 100644 --- a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/FieldsWriter.java +++ b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/FieldsWriter.java @@ -3,4 +3,5 @@ public interface FieldsWriter extends JavaCodeWriter { void writeStaticThizField(String className); void writePublicRuntimeIdField(); + void writeRuntimeTagField(); } diff --git a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/MethodsWriter.java b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/MethodsWriter.java index 888c8c28..95a6049d 100644 --- a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/MethodsWriter.java +++ b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/MethodsWriter.java @@ -8,5 +8,6 @@ public interface MethodsWriter extends JavaCodeWriter { void writeGetInstanceMethod(String className); void writeInternalRuntimeEqualsMethod(); void writeInternalRuntimeHashCodeMethod(); + void writeInternalRuntimeTagAccessorMethods(); void writeInternalServiceOnCreateMethod(); } diff --git a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/ClassWriterImpl.java b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/ClassWriterImpl.java index d91c1f4e..092ae0f0 100644 --- a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/ClassWriterImpl.java +++ b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/ClassWriterImpl.java @@ -11,6 +11,7 @@ public class ClassWriterImpl implements ClassWriter { private static final String PUBLIC_CLASS_KEYWORD = "public class"; private static final String JAVASCRIPT_IMPLEMENTATION_FILE_NAME_PATTERN = "@com.tns.JavaScriptImplementation(javaScriptFile = \"./%s\")"; private static final String NATIVESCRIPT_HASHCODE_PROVIDER_INTERFACE_NAME = "com.tns.NativeScriptHashCodeProvider"; + private static final String NATIVESCRIPT_RUNTIME_BOUND_INTERFACE_NAME = "com.tns.NativeScriptRuntimeBound"; private static final String NOT_EXTENDING_ANY_CLASS_MESSAGE = "Not extending any class!"; private final Writer writer; @@ -42,6 +43,9 @@ public void writeBeginningOfChildClass(String className, String extendedClassNam writer.write(IMPLEMENTS_KEYWORD); writer.write(SPACE_LITERAL); writer.write(NATIVESCRIPT_HASHCODE_PROVIDER_INTERFACE_NAME); + writer.write(COMMA_LITERAL); + writer.write(SPACE_LITERAL); + writer.write(NATIVESCRIPT_RUNTIME_BOUND_INTERFACE_NAME); if (!isEmpty(implementedInterfacesNames) && !isEmpty(implementedInterfacesNames.get(0))) { writer.write(COMMA_LITERAL); diff --git a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/FieldsWriterImpl.java b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/FieldsWriterImpl.java index d46fc59d..e213f79e 100644 --- a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/FieldsWriterImpl.java +++ b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/FieldsWriterImpl.java @@ -8,6 +8,8 @@ public class FieldsWriterImpl implements FieldsWriter { private static final String THIZ_KEYWORD = "thiz"; private static final String RUNTIME_ID_KEYWORD = "runtimeId"; + private static final String RUNTIME_TAG_FIELD_DECLARATION = "private volatile int runtimeTag__ns;"; + private static final String OBJECT_ID_FIELD_DECLARATION = "private int objectId__ns;"; private final Writer writer; @@ -44,4 +46,13 @@ public void writePublicRuntimeIdField() { writer.writeln(END_OF_STATEMENT_LITERAL); writer.writeln(); } + + @Override + public void writeRuntimeTagField() { + writer.write(TABULATION_LITERAL); + writer.writeln(RUNTIME_TAG_FIELD_DECLARATION); + writer.write(TABULATION_LITERAL); + writer.writeln(OBJECT_ID_FIELD_DECLARATION); + writer.writeln(); + } } diff --git a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/MethodsWriterImpl.java b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/MethodsWriterImpl.java index 57752455..c3f5d8f8 100644 --- a/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/MethodsWriterImpl.java +++ b/platforms/android/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/MethodsWriterImpl.java @@ -47,6 +47,14 @@ public class MethodsWriterImpl implements MethodsWriter { private static final String INTERNAL_RUNTIME_EQUALS_METHOD_SIGNATURE = "public boolean equals__super(java.lang.Object other)"; private static final String INTERNAL_RUNTIME_HASHCODE_METHOD_SIGNATURE = "public int hashCode__super()"; + private static final String INTERNAL_RUNTIME_GET_RUNTIME_TAG_METHOD_SIGNATURE = "public int getRuntimeTag__ns()"; + private static final String INTERNAL_RUNTIME_GET_RUNTIME_TAG_RETURN_STATEMENT = "return runtimeTag__ns;"; + private static final String INTERNAL_RUNTIME_SET_RUNTIME_TAG_METHOD_SIGNATURE = "public void setRuntimeTag__ns(int tag)"; + private static final String INTERNAL_RUNTIME_SET_RUNTIME_TAG_ASSIGNMENT = "runtimeTag__ns = tag;"; + private static final String INTERNAL_RUNTIME_GET_OBJECT_ID_METHOD_SIGNATURE = "public int getObjectId__ns()"; + private static final String INTERNAL_RUNTIME_GET_OBJECT_ID_RETURN_STATEMENT = "return objectId__ns;"; + private static final String INTERNAL_RUNTIME_SET_OBJECT_ID_METHOD_SIGNATURE = "public void setObjectId__ns(int id)"; + private static final String INTERNAL_RUNTIME_SET_OBJECT_ID_ASSIGNMENT = "objectId__ns = id;"; private static final String INTERNAL_SERVICES_ONCREATE_METHOD_SIGNATURE = "public void " + ON_CREATE_METHOD_NAME + "()"; private static final String RETURN_KEYWORD = "return"; @@ -398,6 +406,14 @@ public void writeInternalRuntimeHashCodeMethod() { writeInternalRuntimeMethod(INTERNAL_RUNTIME_HASHCODE_METHOD_SIGNATURE, INTERNAL_RUNTIME_HASHCODE_METHOD_RETURN_STATEMENT); } + @Override + public void writeInternalRuntimeTagAccessorMethods() { + writeInternalRuntimeMethod(INTERNAL_RUNTIME_GET_RUNTIME_TAG_METHOD_SIGNATURE, INTERNAL_RUNTIME_GET_RUNTIME_TAG_RETURN_STATEMENT); + writeInternalRuntimeMethod(INTERNAL_RUNTIME_SET_RUNTIME_TAG_METHOD_SIGNATURE, INTERNAL_RUNTIME_SET_RUNTIME_TAG_ASSIGNMENT); + writeInternalRuntimeMethod(INTERNAL_RUNTIME_GET_OBJECT_ID_METHOD_SIGNATURE, INTERNAL_RUNTIME_GET_OBJECT_ID_RETURN_STATEMENT); + writeInternalRuntimeMethod(INTERNAL_RUNTIME_SET_OBJECT_ID_METHOD_SIGNATURE, INTERNAL_RUNTIME_SET_OBJECT_ID_ASSIGNMENT); + } + private void writeInternalRuntimeMethod(String signature, String returnStatement) { writer.write(signature); writer.write(OPENING_CURLY_BRACKET_LITERAL); diff --git a/platforms/android/test-app/build-tools/static-binding-generator/src/test/java/com/tns/NativeScriptRuntimeBound.java b/platforms/android/test-app/build-tools/static-binding-generator/src/test/java/com/tns/NativeScriptRuntimeBound.java new file mode 100644 index 00000000..adb75c29 --- /dev/null +++ b/platforms/android/test-app/build-tools/static-binding-generator/src/test/java/com/tns/NativeScriptRuntimeBound.java @@ -0,0 +1,14 @@ +package com.tns; + +public interface NativeScriptRuntimeBound { + int getRuntimeTag__ns(); + + void setRuntimeTag__ns(int tag); + + default int getObjectId__ns() { + return -1; + } + + default void setObjectId__ns(int id) { + } +} diff --git a/platforms/android/test-app/build-tools/static-binding-generator/src/test/java/org/nativescript/staticbindinggenerator/test/GeneratorTest.java b/platforms/android/test-app/build-tools/static-binding-generator/src/test/java/org/nativescript/staticbindinggenerator/test/GeneratorTest.java index 689f3221..cc8f1486 100644 --- a/platforms/android/test-app/build-tools/static-binding-generator/src/test/java/org/nativescript/staticbindinggenerator/test/GeneratorTest.java +++ b/platforms/android/test-app/build-tools/static-binding-generator/src/test/java/org/nativescript/staticbindinggenerator/test/GeneratorTest.java @@ -53,7 +53,29 @@ public void testCanCompileBinding() throws Exception { Class helloClass = InMemoryJavaCompiler.compile(binding.getClassname(), sourceCode.toString(), options); Assert.assertNotNull(helloClass); - Assert.assertEquals(3, helloClass.getDeclaredMethods().length); + Assert.assertEquals(7, helloClass.getDeclaredMethods().length); + } + + @Test + public void testBindingCarriesARuntimeTagAndObjectId() throws Exception { + List lines = Utils.getDataRowsFromResource("datarow-named-extend.txt"); + DataRow dataRow = new DataRow(lines.get(0)); + + Generator generator = new Generator(null, new ArrayList()); + Binding binding = generator.generateBinding(dataRow); + + Iterable options = new ArrayList(Arrays.asList("-cp", dependenciesDir)); + Class boundClass = InMemoryJavaCompiler.compile(binding.getClassname(), binding.getContent(), options); + + Assert.assertTrue(com.tns.NativeScriptRuntimeBound.class.isAssignableFrom(boundClass)); + Assert.assertTrue(java.lang.reflect.Modifier.isVolatile(boundClass.getDeclaredField("runtimeTag__ns").getModifiers())); + + com.tns.NativeScriptRuntimeBound instance = (com.tns.NativeScriptRuntimeBound) boundClass.getDeclaredConstructor().newInstance(); + Assert.assertEquals(0, instance.getRuntimeTag__ns()); + instance.setRuntimeTag__ns(3); + instance.setObjectId__ns(42); + Assert.assertEquals(3, instance.getRuntimeTag__ns()); + Assert.assertEquals(42, instance.getObjectId__ns()); } @Test @@ -79,7 +101,7 @@ public void testCanCompileBindingOfInterfaceWithStaticInitializer() throws Excep Class helloClass = InMemoryJavaCompiler.compile("com.tns.gen.com.example.MyInterface", sourceCode.toString(), options); Assert.assertNotNull(helloClass); - Assert.assertEquals(3, helloClass.getDeclaredMethods().length); // 3 methods (includes 'hashCode__super' and 'equals__super') + Assert.assertEquals(7, helloClass.getDeclaredMethods().length); // 7 methods (includes 'hashCode__super', 'equals__super' and the runtime tag and object id accessors) } @Test @@ -127,7 +149,7 @@ public void testCanCompileBindingClassExtendingAnExtendedClassWithMethodsWithThe Class ComplexClass = InMemoryJavaCompiler.compile(binding.getClassname(), sourceCode.toString(), options); Assert.assertNotNull(ComplexClass); - Assert.assertEquals(4, ComplexClass.getDeclaredMethods().length); // 1 + constructor + (equals + hashcode) + Assert.assertEquals(8, ComplexClass.getDeclaredMethods().length); // 1 + constructor + (equals + hashcode) + (runtime tag and object id accessors) } @Test diff --git a/platforms/android/test-app/runtime-binding-generator/src/main/java/com/tns/NativeScriptRuntimeBound.java b/platforms/android/test-app/runtime-binding-generator/src/main/java/com/tns/NativeScriptRuntimeBound.java new file mode 100644 index 00000000..adb75c29 --- /dev/null +++ b/platforms/android/test-app/runtime-binding-generator/src/main/java/com/tns/NativeScriptRuntimeBound.java @@ -0,0 +1,14 @@ +package com.tns; + +public interface NativeScriptRuntimeBound { + int getRuntimeTag__ns(); + + void setRuntimeTag__ns(int tag); + + default int getObjectId__ns() { + return -1; + } + + default void setObjectId__ns(int id) { + } +} diff --git a/platforms/android/test-app/runtime-binding-generator/src/main/java/com/tns/bindings/Dump.java b/platforms/android/test-app/runtime-binding-generator/src/main/java/com/tns/bindings/Dump.java index 3afcefcf..f2b10927 100644 --- a/platforms/android/test-app/runtime-binding-generator/src/main/java/com/tns/bindings/Dump.java +++ b/platforms/android/test-app/runtime-binding-generator/src/main/java/com/tns/bindings/Dump.java @@ -23,6 +23,8 @@ public class Dump { static final String runtimeClass = LCOM_TNS_RUNTIME; static final String callJSMethodName = "callJSMethod"; static final String initInstanceMethodName = "initInstance"; + static final String RUNTIME_TAG_FIELD_NAME = "runtimeTag__ns"; + static final String OBJECT_ID_FIELD_NAME = "objectId__ns"; static final StringBuffer methodDescriptorBuilder = new StringBuffer(); @@ -498,6 +500,28 @@ private void generateMethods(ClassVisitor cv, ClassDescriptor classTo, MethodDes generateEqualsSuper(cv); generateHashCodeSuper(cv); + generateIntGetter(cv, tnsClassSignature, "getRuntimeTag__ns", RUNTIME_TAG_FIELD_NAME); + generateIntSetter(cv, tnsClassSignature, "setRuntimeTag__ns", RUNTIME_TAG_FIELD_NAME); + generateIntGetter(cv, tnsClassSignature, "getObjectId__ns", OBJECT_ID_FIELD_NAME); + generateIntSetter(cv, tnsClassSignature, "setObjectId__ns", OBJECT_ID_FIELD_NAME); + } + + private void generateIntGetter(ClassVisitor cv, String tnsClassSignature, String methodName, String fieldName) { + MethodVisitor mv = cv.visitMethod(org.ow2.asmdex.Opcodes.ACC_PUBLIC, methodName, "I", null, null); + mv.visitCode(); + mv.visitMaxs(2, 0); + mv.visitFieldInsn(org.ow2.asmdex.Opcodes.INSN_IGET, tnsClassSignature, fieldName, "I", 0, 1); + mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN, 0); + mv.visitEnd(); + } + + private void generateIntSetter(ClassVisitor cv, String tnsClassSignature, String methodName, String fieldName) { + MethodVisitor mv = cv.visitMethod(org.ow2.asmdex.Opcodes.ACC_PUBLIC, methodName, "VI", null, null); + mv.visitCode(); + mv.visitMaxs(2, 0); + mv.visitFieldInsn(org.ow2.asmdex.Opcodes.INSN_IPUT, tnsClassSignature, fieldName, "I", 1, 0); + mv.visitInsn(org.ow2.asmdex.Opcodes.INSN_RETURN_VOID); + mv.visitEnd(); } private void generateEqualsSuper(ClassVisitor cv) { @@ -814,10 +838,14 @@ private void generateFields(ClassVisitor cv) { // Add runtimeId field fv = cv.visitField(org.ow2.asmdex.Opcodes.ACC_PUBLIC, "runtimeId", "I", null, null); fv.visitEnd(); + fv = cv.visitField(org.ow2.asmdex.Opcodes.ACC_PRIVATE | org.ow2.asmdex.Opcodes.ACC_VOLATILE, RUNTIME_TAG_FIELD_NAME, "I", null, null); + fv.visitEnd(); + fv = cv.visitField(org.ow2.asmdex.Opcodes.ACC_PRIVATE, OBJECT_ID_FIELD_NAME, "I", null, null); + fv.visitEnd(); } - static final String[] classImplentedInterfaces = new String[] { "Lcom/tns/NativeScriptHashCodeProvider;" }; - static final String[] interfaceImplementedInterfaces = new String[] { "Lcom/tns/NativeScriptHashCodeProvider;", "" }; + static final String[] classImplentedInterfaces = new String[] { "Lcom/tns/NativeScriptHashCodeProvider;", "Lcom/tns/NativeScriptRuntimeBound;" }; + static final String[] interfaceImplementedInterfaces = new String[] { "Lcom/tns/NativeScriptHashCodeProvider;", "Lcom/tns/NativeScriptRuntimeBound;", "" }; private ClassVisitor generateClass(ApplicationWriter aw, ClassDescriptor classTo, String classSignature, String tnsClassSignature, HashSet implementedInterfaces, AnnotationDescriptor[] annotations) { ClassVisitor cv; @@ -827,7 +855,7 @@ private ClassVisitor generateClass(ApplicationWriter aw, ClassDescriptor classTo ArrayList interfacesToImplement = new ArrayList(Arrays.asList(classImplentedInterfaces)); if (classTo.isInterface()) { - interfaceImplementedInterfaces[1] = classSignature; //new String[] { "Lcom/tns/NativeScriptHashCodeProvider;", classSignature }; + interfaceImplementedInterfaces[2] = classSignature; //new String[] { "Lcom/tns/NativeScriptHashCodeProvider;", classSignature }; for (String interfaceToImpl : interfaceImplementedInterfaces) { if (!interfacesToImplement.contains(interfaceToImpl)) { interfacesToImplement.add(interfaceToImpl); diff --git a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java index 65a60eba..e8e06744 100644 --- a/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/platforms/android/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -219,6 +219,26 @@ public int compare(Method lhs, Method rhs) { private static AtomicInteger nextRuntimeId = new AtomicInteger(0); private final static ThreadLocal currentRuntime = new ThreadLocal(); private final static Map runtimeCache = new ConcurrentHashMap<>(); + private static volatile Runtime[] runtimesById = new Runtime[8]; + private static final int MAX_INDEXED_RUNTIME_ID = 1024; + + private static synchronized void indexRuntime(int runtimeId, Runtime runtime) { + if (runtimeId < 0 || runtimeId >= MAX_INDEXED_RUNTIME_ID) { + return; + } + Runtime[] index = runtimesById; + index = Arrays.copyOf(index, Math.max(index.length, Integer.highestOneBit(runtimeId) * 2)); + index[runtimeId] = runtime; + runtimesById = index; + } + + private static Runtime runtimeForId(int runtimeId) { + Runtime[] index = runtimesById; + if (runtimeId >= 0 && runtimeId < index.length) { + return index[runtimeId]; + } + return runtimeCache.get(runtimeId); + } public static boolean nativeLibraryLoaded; private static final ClassStorageService classStorageService = new ClassStorageServiceImpl(ClassCacheImpl.INSTANCE, ClassLoadersCollectionImpl.INSTANCE); @@ -286,6 +306,7 @@ public Runtime(StaticConfiguration config, DynamicConfiguration dynamicConfigura classResolver = new ClassResolver(classStorageService); runtimeCache.put(this.runtimeId, this); + indexRuntime(this.runtimeId, this); gcListener = GcListener.getInstance(config.appConfig.getMemoryCheckInterval(), config.appConfig.getFreeMemoryRatio()); currentRuntime.set(this); @@ -306,7 +327,7 @@ public static Runtime getCurrentRuntime() { // Attempt to retrieve the runtime id from the currently // entered V8 isolate int runtimeId = getCurrentRuntimeId(); - runtime = runtimeCache.get(runtimeId); + runtime = runtimeForId(runtimeId); } return runtime; @@ -486,6 +507,7 @@ static Runtime attachToHostRuntime(StaticConfiguration config, long hostRuntimeP // the instance, so a failed bootstrap must not leave a stale one // reachable through the caches. runtimeCache.remove(runtime.getRuntimeId()); + indexRuntime(runtime.getRuntimeId(), null); currentRuntime.remove(); GcListener.unsubscribe(runtime); throw t; @@ -579,6 +601,7 @@ thread during shutdown, and by detach(). @RuntimeCallable public static void detachRuntime(int runtimeId) { Runtime runtime = runtimeCache.remove(runtimeId); + indexRuntime(runtimeId, null); if (runtime != null) { GcListener.unsubscribe(runtime); @@ -603,6 +626,7 @@ private static Runtime initRuntime(DynamicConfiguration dynamicConfiguration) { // failed bootstrap doesn't leave a stale, half-initialized runtime // reachable through the caches runtimeCache.remove(runtime.getRuntimeId()); + indexRuntime(runtime.getRuntimeId(), null); currentRuntime.remove(); GcListener.unsubscribe(runtime); throw t; @@ -838,14 +862,26 @@ public static void initInstance(Object instance) { runtime.currentObjectId = -1; runtime.makeInstanceStrong(instance, objectId); } else { - runtime.createJSInstance(instance); + objectId = runtime.createJSInstance(instance); } + + recordOwningRuntime(instance, runtime.getRuntimeId(), objectId); } finally { frame.close(); } } - private void createJSInstance(Object instance) { + private static void recordOwningRuntime(Object instance, int runtimeId, int objectId) { + if (instance instanceof NativeScriptRuntimeBound) { + NativeScriptRuntimeBound bound = (NativeScriptRuntimeBound) instance; + if (bound.getRuntimeTag__ns() == 0) { + bound.setObjectId__ns(objectId); + bound.setRuntimeTag__ns(runtimeId + 1); + } + } + } + + private int createJSInstance(Object instance) { int javaObjectID = generateNewObjectId(getRuntimeId()); makeInstanceStrong(instance, javaObjectID); @@ -870,6 +906,8 @@ private void createJSInstance(Object instance) { if (logger.isEnabled()) { logger.write("JSInstance for " + instance.getClass().toString() + " created with overrides"); } + + return javaObjectID; } @RuntimeCallable @@ -1123,12 +1161,31 @@ public static Object callJSMethodWithDelay(int runtimeId, Object javaObject, Str } public static Object callJSMethod(int runtimeId, Object javaObject, String methodName, Class retType, boolean isConstructor, long delay, Object... args) throws NativeScriptException { - Runtime runtime = Runtime.runtimeCache.get(runtimeId); + Runtime runtime = null; + Integer javaObjectID = null; + + if (javaObject instanceof NativeScriptRuntimeBound) { + NativeScriptRuntimeBound bound = (NativeScriptRuntimeBound) javaObject; + int tag = bound.getRuntimeTag__ns(); + if (tag != 0) { + runtime = runtimeForId(tag - 1); + int hint = bound.getObjectId__ns(); + if (runtime != null && hint != ObjectTable.NO_ID && runtime.objectTable.get(hint) == javaObject) { + javaObjectID = hint; + } + } + } + + if (runtime == null) { + runtime = runtimeForId(runtimeId); + } // Resolve the object's id on the found runtime once and reuse it (the common // path previously looked it up here for the ownership check AND again in // callJSMethodImpl). Re-resolve only when we switch to a different runtime. - Integer javaObjectID = (runtime != null) ? runtime.getJavaObjectID(javaObject) : null; + if (javaObjectID == null && runtime != null) { + javaObjectID = runtime.getJavaObjectID(javaObject); + } // If we didn't find a runtime by id, or the one we found doesn't own this // object, locate the runtime that actually created it. This happens when a From 56281b4e6a93f5605bb9b00c2da7e06abdea8f4e Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 10:05:17 +0500 Subject: [PATCH 14/16] perf(android): switch large static field sets to dictionary mode and cache their final fields --- .../ffi/jni/jsi/metadata/MetadataNode.cpp | 47 +++++++++++++---- .../ffi/jni/napi/metadata/MetadataNode.cpp | 52 +++++++++++++++++-- .../ffi/jni/napi/metadata/MetadataNode.h | 2 + 3 files changed, 88 insertions(+), 13 deletions(-) diff --git a/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp b/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp index 551161a7..4c7e93b7 100644 --- a/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp +++ b/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp @@ -60,6 +60,15 @@ JsValue Guarded(JsRuntime &rt, Fn &&fn) { } } +constexpr size_t kManyMembers = 64; + +void MoveToDictionaryMode(JsRuntime &rt, JsObject &object) { + object.setProperty(rt, "__ns_dictionary_a", true); + object.setProperty(rt, "__ns_dictionary_b", true); + js_util::delete_property(rt, JsValue(rt, object), js_util::to_js_string(rt, "__ns_dictionary_a")); + js_util::delete_property(rt, JsValue(rt, object), js_util::to_js_string(rt, "__ns_dictionary_b")); +} + // Defines `name` on `object` as an accessor backed by the given host functions. void DefineAccessor(JsRuntime &rt, const JsObject &object, const char *name, engine::HostFunctionType getter, engine::HostFunctionType setter) { @@ -1436,20 +1445,40 @@ std::vector MetadataNode::SetClassMembersFro // get candidates from static fields metadata auto staticFieldCout = *reinterpret_cast(curPtr); curPtr += sizeof(uint16_t); + bool manyFields = staticFieldCout > kManyMembers; + if (manyFields) { + MoveToDictionaryMode(rt, constructor); + } for (auto i = 0; i < staticFieldCout; i++) { auto entry = MetadataReader::ReadStaticFieldEntry(&curPtr); auto &fieldName = entry.getName(); auto fieldInfo = new FieldCallbackData(entry); fieldInfo->objectManager = objectManager; - DefineAccessor(rt, constructor, fieldName.c_str(), - [fieldInfo](JsRuntime &rt, const JsValue &thisVal, const JsValue *, - size_t) -> JsValue { - return FieldAccessorGetterCallback(rt, thisVal, fieldInfo); - }, - [fieldInfo](JsRuntime &rt, const JsValue &thisVal, const JsValue *args, - size_t argc) -> JsValue { - return FieldAccessorSetterCallback(rt, thisVal, args, argc, fieldInfo); - }); + if (manyFields && fieldInfo->metadata.getIsFinal()) { + DefineAccessor(rt, constructor, fieldName.c_str(), + [fieldInfo](JsRuntime &rt, const JsValue &thisVal, const JsValue *, + size_t) -> JsValue { + JsValue value = FieldAccessorGetterCallback(rt, thisVal, fieldInfo); + if (thisVal.isObject()) { + js_util::define_property_value( + rt, thisVal.asObjectBorrowed(rt), + fieldInfo->metadata.getName().c_str(), value, + true, false, false); + } + return value; + }, + nullptr); + } else { + DefineAccessor(rt, constructor, fieldName.c_str(), + [fieldInfo](JsRuntime &rt, const JsValue &thisVal, const JsValue *, + size_t) -> JsValue { + return FieldAccessorGetterCallback(rt, thisVal, fieldInfo); + }, + [fieldInfo](JsRuntime &rt, const JsValue &thisVal, const JsValue *args, + size_t argc) -> JsValue { + return FieldAccessorSetterCallback(rt, thisVal, args, argc, fieldInfo); + }); + } cache->fieldCallbackData.push_back(fieldInfo); } diff --git a/NativeScript/ffi/jni/napi/metadata/MetadataNode.cpp b/NativeScript/ffi/jni/napi/metadata/MetadataNode.cpp index ac10b824..ff4c23c3 100644 --- a/NativeScript/ffi/jni/napi/metadata/MetadataNode.cpp +++ b/NativeScript/ffi/jni/napi/metadata/MetadataNode.cpp @@ -24,6 +24,21 @@ using namespace std; namespace { +constexpr size_t kManyMembers = 64; + +void MoveToDictionaryMode(napi_env env, napi_value object) { + napi_value first; + napi_value second; + napi_create_string_utf8(env, "__ns_dictionary_a", NAPI_AUTO_LENGTH, &first); + napi_create_string_utf8(env, "__ns_dictionary_b", NAPI_AUTO_LENGTH, &second); + napi_value marker = napi_util::get_true(env); + bool deleted; + napi_set_property(env, object, first, marker); + napi_set_property(env, object, second, marker); + napi_delete_property(env, object, first, &deleted); + napi_delete_property(env, object, second, &deleted); +} + napi_value EnsureConstructorThis(napi_env env, napi_value jsThis, napi_value prototype) { if (!napi_util::is_null_or_undefined(env, jsThis)) { return jsThis; @@ -1700,14 +1715,22 @@ std::vector MetadataNode::SetClassMembersFro // get candidates from static fields metadata auto staticFieldCout = *reinterpret_cast(curPtr); curPtr += sizeof(uint16_t); + bool manyFields = staticFieldCout > kManyMembers; + if (manyFields) { + MoveToDictionaryMode(env, constructor); + } for (auto i = 0; i < staticFieldCout; i++) { auto entry = MetadataReader::ReadStaticFieldEntry(&curPtr); auto &fieldName = entry.getName(); auto fieldInfo = new FieldCallbackData(entry); - napi_value method; - napi_util::define_property(env, constructor, fieldName.c_str(), nullptr, - FieldAccessorGetterCallback, FieldAccessorSetterCallback, - fieldInfo); + if (manyFields && fieldInfo->metadata.getIsFinal()) { + napi_util::define_property(env, constructor, fieldName.c_str(), nullptr, + FinalStaticFieldGetterCallback, nullptr, fieldInfo); + } else { + napi_util::define_property(env, constructor, fieldName.c_str(), nullptr, + FieldAccessorGetterCallback, FieldAccessorSetterCallback, + fieldInfo); + } MetadataNode::GetMetadataNodeCache(env)->fieldCallbackData.push_back(fieldInfo); fieldInfo->objectManager = objectManager; } @@ -2157,6 +2180,27 @@ napi_value MetadataNode::FieldAccessorGetterCallback(napi_env env, napi_callback return UNDEFINED; } +napi_value MetadataNode::FinalStaticFieldGetterCallback(napi_env env, napi_callback_info info) { + napi_value value = FieldAccessorGetterCallback(env, info); + + bool exceptionPending = false; + napi_is_exception_pending(env, &exceptionPending); + if (exceptionPending || value == nullptr) { + return value; + } + + napi_value jsThis = nullptr; + void *data = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &jsThis, &data); + if (jsThis != nullptr && data != nullptr) { + auto fieldData = reinterpret_cast(data); + napi_util::define_property_value(env, jsThis, fieldData->metadata.getName().c_str(), value, + napi_enumerable); + } + + return value; +} + napi_ref propRef = nullptr; napi_value MetadataNode::FieldAccessorSetterCallback(napi_env env, napi_callback_info info) { NAPI_CALLBACK_BEGIN(1); diff --git a/NativeScript/ffi/jni/napi/metadata/MetadataNode.h b/NativeScript/ffi/jni/napi/metadata/MetadataNode.h index 7aaf11e7..6ba334af 100644 --- a/NativeScript/ffi/jni/napi/metadata/MetadataNode.h +++ b/NativeScript/ffi/jni/napi/metadata/MetadataNode.h @@ -175,6 +175,8 @@ class MetadataNode { static napi_value FieldAccessorGetterCallback(napi_env env, napi_callback_info info); + static napi_value FinalStaticFieldGetterCallback(napi_env env, napi_callback_info info); + static napi_value FieldAccessorSetterCallback(napi_env env, napi_callback_info info); static napi_value ArraySetterCallback(napi_env env, napi_callback_info info); From 124bf430fbc847fabb70cd85a78cfc4a408fa73f Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 10:05:17 +0500 Subject: [PATCH 15/16] perf(android): create Java instance methods as non-constructors on V8 --- NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp | 2 +- NativeScript/jsi/v8/V8HostObjects.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp b/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp index 4c7e93b7..d946da25 100644 --- a/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp +++ b/NativeScript/ffi/jni/jsi/metadata/MetadataNode.cpp @@ -1409,7 +1409,7 @@ std::vector MetadataNode::SetClassMembersFro if (methodName != lastMethodName) { callbackData = new MethodCallbackData(this); cache->methodCallbackData.push_back(callbackData); - auto method = JsFunction::createFromHostFunction( + auto method = JsFunction::createFromHostConstructor( rt, engine::PropNameID::forAscii(rt, methodName), 0, [callbackData](JsRuntime &rt, const JsValue &thisVal, const JsValue *args, size_t argc) -> JsValue { diff --git a/NativeScript/jsi/v8/V8HostObjects.cpp b/NativeScript/jsi/v8/V8HostObjects.cpp index 245fad0c..8c75db2a 100644 --- a/NativeScript/jsi/v8/V8HostObjects.cpp +++ b/NativeScript/jsi/v8/V8HostObjects.cpp @@ -447,7 +447,7 @@ Function Function::createFromHostFunction(Runtime& runtime, const PropNameID& na v8engine::throwV8Exception(info.GetIsolate(), exception); } }, - data); + data, v8::Local(), 0, v8::ConstructorBehavior::kThrow); v8::Local function = functionTemplate->GetFunction(runtime.context()).ToLocalChecked(); std::string functionName = name.utf8(runtime); From 58ef71606f87cf79ad0a63fe34bfec61a952719a Mon Sep 17 00:00:00 2001 From: Ammar Ahmed Date: Wed, 11 Nov 2026 10:05:25 +0500 Subject: [PATCH 16/16] test(android): add specs and benchmark rows for the JNI bridge changes --- .../main/assets/app/marshalling-benchmark.js | 5 ++ .../app/src/main/assets/app/tests/testGC.js | 62 +++++++++++++++- .../src/main/assets/app/tests/testMetadata.js | 73 ++++++++++++++++++- .../com/tns/tests/NestedConstruction.java | 16 ++++ .../java/com/tns/tests/WrapperHolder.java | 5 ++ 5 files changed, 159 insertions(+), 2 deletions(-) create mode 100644 platforms/android/test-app/app/src/main/java/com/tns/tests/NestedConstruction.java create mode 100644 platforms/android/test-app/app/src/main/java/com/tns/tests/WrapperHolder.java diff --git a/platforms/android/test-app/app/src/main/assets/app/marshalling-benchmark.js b/platforms/android/test-app/app/src/main/assets/app/marshalling-benchmark.js index bfbc3048..f5f6a637 100644 --- a/platforms/android/test-app/app/src/main/assets/app/marshalling-benchmark.js +++ b/platforms/android/test-app/app/src/main/assets/app/marshalling-benchmark.js @@ -42,6 +42,11 @@ function buildSuite() { var b = new org.nativescript.Benchmarks(); return [ + { name: "First access android.R.attr", iterations: 1, action: function () { void android.R.attr.textColor; } }, + { name: "First access android.view", iterations: 1, action: function () { void android.view.View; } }, + { name: "First access TextView", iterations: 1, action: function () { void android.widget.TextView; } }, + { name: "Package member read", action: function () { for (var i = 0; i < 1e6; i++) void android.widget.TextView; } }, + { name: "Static final field read", action: function () { for (var i = 0; i < 1e6; i++) void android.R.attr.textColor; } }, { name: "Void Method on instance", action: function () { for (var i = 0; i < 1e6; i++) b.voidMethod1(); } }, { name: "Field on instance", action: function () { for (var i = 0; i < 1e6; i++) void b.InstanceField; } }, { name: "Int Field on instance", action: function () { for (var i = 0; i < 1e6; i++) void b.IntFieldInstance; } }, diff --git a/platforms/android/test-app/app/src/main/assets/app/tests/testGC.js b/platforms/android/test-app/app/src/main/assets/app/tests/testGC.js index 89e33762..e4f659dd 100644 --- a/platforms/android/test-app/app/src/main/assets/app/tests/testGC.js +++ b/platforms/android/test-app/app/src/main/assets/app/tests/testGC.js @@ -317,4 +317,64 @@ describeFunc("Tests garbage collection", function () { test.postCallback(); }); -}); \ No newline at end of file + + describe("collected wrappers waiting for a flush", function () { + var Holder = com.tns.tests.WrapperHolder; + + function collectJava() { + for (var i = 0; i < 3; i++) { + java.lang.Runtime.getRuntime().gc(); + java.lang.System.runFinalization(); + } + } + + afterEach(function () { + Holder.held = null; + }); + + it("keep a callback's error when wrappers were collected after its last Java call", function () { + var callable = new java.util.concurrent.Callable({ + call: function () { + for (var i = 0; i < 2000; i++) { + new java.lang.Object(); + } + gc(); + throw new Error("thrown with a batch pending"); + } + }); + var task = new java.util.concurrent.FutureTask(callable); + task.run(); + + expect(task.isDone()).toBe(true); + expect(function () { task.get(); }).toThrow(); + }); + + it("keep the Java object of a wrapper handed back to JS before the flush", function () { + (function () { + Holder.held = new java.lang.StringBuilder("reacquired"); + })(); + gc(); + var again = Holder.held; + Holder.held = null; + collectJava(); + + expect(again.toString()).toBe("reacquired"); + }); + + it("keep a wrapper handed back to JS while its liveness check is queued", function () { + (function () { + Holder.held = new java.lang.StringBuilder("checked"); + })(); + gc(); + collectJava(); + gc(); + var again = Holder.held; + collectJava(); + + expect(again.toString()).toBe("checked"); + again = null; + gc(); + collectJava(); + }); + }); +}); diff --git a/platforms/android/test-app/app/src/main/assets/app/tests/testMetadata.js b/platforms/android/test-app/app/src/main/assets/app/tests/testMetadata.js index 1d746920..8d3f3f15 100644 --- a/platforms/android/test-app/app/src/main/assets/app/tests/testMetadata.js +++ b/platforms/android/test-app/app/src/main/assets/app/tests/testMetadata.js @@ -35,4 +35,75 @@ describe("Tests metadata", function () { var expected = 5; expect(keywordClass.getValue5()).toBe(expected); }); -}); \ No newline at end of file +}); + +describe("Java members", function () { + it("keep static methods constructible, so new on a static factory returns its object", function () { + var id = new java.util.UUID.randomUUID(); + + expect(id instanceof java.util.UUID).toBe(true); + }); + + it("leave class constructors constructible", function () { + var MyObject = java.lang.Object.extend({ toString: function () { return "mine"; } }); + + expect(new java.util.ArrayList().size()).toBe(0); + expect(new MyObject().toString()).toBe("mine"); + expect(java.util.UUID.randomUUID() instanceof java.util.UUID).toBe(true); + }); + + it("read the final static fields of a class with many of them", function () { + var first = android.R.attr.textColor; + + expect(typeof first).toBe("number"); + expect(android.R.attr.textColor).toBe(first); + }); +}); + +describe("Java object wrappers", function () { + it("leave an extended instance Java creates during a JS construction its own JS object", function () { + var Inner = java.lang.Object.extend({ toString: function () { return "inner"; } }); + var Outer = com.tns.tests.NestedConstruction.extend({ toString: function () { return "outer"; } }); + var outer = new Outer(new Inner().getClass(), null); + + expect(String(outer.toString())).toBe("outer"); + expect(String(outer.getCreated().toString())).toBe("inner"); + }); + + it("keep a JS construction's instance when a callback constructs another during it", function () { + var Inner = java.lang.Object.extend({ toString: function () { return "inner"; } }); + var Outer = com.tns.tests.NestedConstruction.extend({ toString: function () { return "outer:" + this.tag; } }); + var made = null; + var outer = new Outer(null, new java.lang.Runnable({ + run: function () { + made = new Inner(); + } + })); + outer.tag = "mine"; + + expect(String(outer.toString())).toBe("outer:mine"); + expect(String(made.toString())).toBe("inner"); + }); + + it("hand back the same wrapper for the same Java object", function () { + var builder = new java.lang.StringBuilder(); + + expect(builder.append("x")).toBe(builder); + }); + + it("stay linked while thousands of later wrappers are collected", function () { + var list = new java.util.ArrayList(); + var first = java.util.UUID.randomUUID(); + list.add(first); + for (var round = 0; round < 3; round++) { + for (var i = 0; i < 3000; i++) { + java.util.UUID.randomUUID(); + } + gc(); + java.lang.System.gc(); + } + + expect(list.get(0)).toBe(first); + expect(String(list.get(0).toString())).toBe(String(first.toString())); + }); +}); diff --git a/platforms/android/test-app/app/src/main/java/com/tns/tests/NestedConstruction.java b/platforms/android/test-app/app/src/main/java/com/tns/tests/NestedConstruction.java new file mode 100644 index 00000000..5c17a181 --- /dev/null +++ b/platforms/android/test-app/app/src/main/java/com/tns/tests/NestedConstruction.java @@ -0,0 +1,16 @@ +package com.tns.tests; + +public class NestedConstruction { + private final Object created; + + public NestedConstruction(Class toCreate, Runnable during) throws Exception { + created = toCreate == null ? null : toCreate.newInstance(); + if (during != null) { + during.run(); + } + } + + public Object getCreated() { + return created; + } +} diff --git a/platforms/android/test-app/app/src/main/java/com/tns/tests/WrapperHolder.java b/platforms/android/test-app/app/src/main/java/com/tns/tests/WrapperHolder.java new file mode 100644 index 00000000..ebaf8c4a --- /dev/null +++ b/platforms/android/test-app/app/src/main/java/com/tns/tests/WrapperHolder.java @@ -0,0 +1,5 @@ +package com.tns.tests; + +public class WrapperHolder { + public static Object held; +}