Search Unity

String.memcpy and String.memset in profiler

Discussion in 'Scripting' started by VesuvianPrime, Oct 5, 2014.

  1. VesuvianPrime

    VesuvianPrime

    Joined:
    Feb 26, 2013
    Posts:
    135
    Hey guys

    I'm currently doing some intensive optimization of my project, and I keep seeing String.memcpy() and String.memset() in the hierarchy:



    These are only 2 of the instances in my sample, but you can clearly see they're being called hundreds of times per frame.

    I understand that simply doing something like this will generate these calls:

    Code (CSharp):
    1. Debug.Log("I'm a new string instance!");
    But the algorithm in the above image deals entirely with bounding boxes. Nowhere am I using strings.

    Does anyone know what is going on here?

    Thanks,
    Ves
     
  2. LogicFlow

    LogicFlow

    Joined:
    Aug 18, 2018
    Posts:
    33
    This affected me lately and may affect others, so I thought I'd provide an answer 7+ years down the line. ;)

    This bug(?) results from using set operations on dereferenced pointers, e.g.
    *((ByteArray256*)bytes) = default;
    I first noticed it when I started porting to
    unsafe
    code.

    Full example to test for yourself, should show up
    String.memset()
    in your profiler:

    Code (CSharp):
    1. using System.Runtime.InteropServices;
    2. using UnityEngine;
    3.  
    4. public class UnsafeTest : MonoBehaviour
    5. {
    6.     byte[] array = new byte[1024];
    7.  
    8.     void Update()
    9.     {
    10.         unsafe { fixed (byte* bytes = array) {
    11.             for (int i = 0; i < 100000; i++)
    12.             *((ByteArray256*) bytes) = default;
    13.    
    14.         }}
    15.     }
    16.  
    17.     [StructLayout(LayoutKind.Explicit)]
    18.     public unsafe struct ByteArray256
    19.     {
    20.         [FieldOffset(0)] public fixed byte bytes[256];
    21.     }
    22. }
    Not sure how important the specifics are, but a large blit / zeroing operation like this tends to trigger it to at least display in the profiler.
     
    Last edited: Dec 18, 2021
  3. MartinTilo

    MartinTilo

    Unity Technologies

    Joined:
    Aug 16, 2017
    Posts:
    2,461
    String memcpy is simply one of the fastest way to copy larger struct types. It looks a bit misleading in the profiler but is technically correct.

    Also the debug log example doesn't have to do any copying at all as that string is compile time constant and passe by ref.