using UnityEngine;
using UnityEditor;
using ArtResource;
using System.Diagnostics;
using GameFramework.Resource;
using UnityGameFramework.Runtime;
using Debug = UnityEngine.Debug;
namespace CrazyMaple.Editor
{
///
/// 对比测试:AssetDatabase vs GameEntry.Resource.LoadAsset
///
public class LoadMethodComparisonTest : EditorWindow
{
[MenuItem("美术工具/性能测试工具/对比加载方式性能")]
public static void ShowWindow()
{
GetWindow("加载方式对比");
}
private void OnGUI()
{
GUILayout.Label("对比测试", EditorStyles.boldLabel);
GUILayout.Space(10);
EditorGUILayout.HelpBox(
"对比两种加载方式的性能差异:\n" +
"1. AssetDatabase.LoadAssetAtPath(Editor专用)\n" +
"2. GameEntry.Resource.LoadAsset(框架统一接口)",
MessageType.Info);
GUILayout.Space(10);
if (GUILayout.Button("运行对比测试", GUILayout.Height(40)))
{
RunComparisonTest();
}
}
private void RunComparisonTest()
{
Debug.Log("========== 加载方式性能对比 ==========");
string[] guids = AssetDatabase.FindAssets("t:ArtTableSO");
if (guids.Length == 0)
{
Debug.LogWarning("未找到任何ArtTableSO");
return;
}
// 清理缓存
Resources.UnloadUnusedAssets();
System.GC.Collect();
foreach (var guid in guids)
{
string path = AssetDatabase.GUIDToAssetPath(guid);
Debug.Log($"\n--- 测试文件: {path} ---");
// 方法1: AssetDatabase(Editor专用,最直接)
Resources.UnloadUnusedAssets();
var sw1 = Stopwatch.StartNew();
var table1 = AssetDatabase.LoadAssetAtPath(path);
sw1.Stop();
Debug.Log($"[AssetDatabase] 加载耗时: {sw1.Elapsed.TotalMilliseconds:F2} ms");
// 方法2: GameEntry.Resource(框架接口,通过EditorResourceComponent)
Resources.UnloadUnusedAssets();
// 检查 GameEntry 是否已初始化
if (GameEntry.Resource == null)
{
Debug.LogWarning("[GameEntry.Resource] GameEntry未初始化,请先运行游戏或在Play模式下测试");
Debug.LogWarning("跳过GameEntry.Resource测试,只显示AssetDatabase结果");
continue;
}
var sw2 = Stopwatch.StartNew();
bool loadCompleted = false;
ArtTableSO table2 = null;
var callbacks = new LoadAssetCallbacks(
(assetName, asset, duration, userData) =>
{
sw2.Stop();
table2 = asset as ArtTableSO;
loadCompleted = true;
Debug.Log($"[GameEntry.Resource] 加载耗时: {sw2.Elapsed.TotalMilliseconds:F2} ms");
Debug.Log($" - Framework报告的duration: {duration:F4} 秒 ({duration * 1000:F2} ms)");
},
(assetName, status, errorMessage, userData) =>
{
sw2.Stop();
loadCompleted = true;
Debug.LogError($"[GameEntry.Resource] 加载失败: {errorMessage}");
}
);
GameEntry.Resource.LoadAsset(path, typeof(ArtTableSO), callbacks);
// 等待异步加载完成(Editor模式下实际是同步的,但需要等待回调)
int timeout = 0;
while (!loadCompleted && timeout < 1000)
{
System.Threading.Thread.Sleep(1);
timeout++;
}
if (!loadCompleted)
{
Debug.LogError("[GameEntry.Resource] 加载超时!");
}
// 对比
if (table1 != null && table2 != null)
{
float ratio = (float)sw2.Elapsed.TotalMilliseconds / (float)sw1.Elapsed.TotalMilliseconds;
Debug.Log($"性能差异: GameEntry.Resource 比 AssetDatabase 慢 {ratio:F1}x");
}
}
Debug.Log("\n========== 测试完成 ==========");
Debug.Log("结论: 如果GameEntry.Resource明显更慢,说明EditorResourceComponent有额外开销");
Debug.Log("建议: 真机/打包后测试,Runtime的AssetBundleResourceComponent性能可能完全不同");
}
}
}