Skip to content

GC allocation in SceneReference.HasValue / Utils.IsValidGuid #117

@Bfihl

Description

@Bfihl

Hey,

I noticed a small GC allocation when using SceneReference.BuildIndex or SceneReference.Path. This happens because SceneReference.HasValue uses Utils.IsValidGuid, which allocates garbage under the hood (most of it comes from string manipulation).

This can be a bit problematic if these properties are used in a hot path. That's why I wrote a GC-free version of it. If you accept pull requests, I can open one if you like. Otherwise, it would be great if you could consider implementing this method. ^^

/// <summary>
/// Returns if the given <paramref name="guid"/> is valid. A valid GUID is 32 chars of hexadecimals.
/// </summary>
public static bool IsValidGuid(this string guid)
{
	if (string.IsNullOrEmpty(guid) || guid.Length != 32)
	{
		return false;
	}

	for (int i = 0; i < guid.Length; i++)
	{
		char c = guid[i];
		bool isValid = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f');

		if (!isValid)
		{
			return false;
		}
	}

	return true;
}

Here is a screenshot without the fix:
Image

Here is one with it. It's way smaller because it doesn't call as many methods internally, but just look at the "GC Alloc" column:
Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions