Start one Coroutine or achieve in the Update funtion

If I want to do something every second,which one is the better in the following two ways and why?

float time=0;
void Start()
{
    StartCoroutine(Test());
}

IEnumerator Test()
{
    while(true)
   {
          //do something
          yield return new WaitForSeconds(1.0f);
   }
}

void Update()
{
    time+=Time.deltTime;
    if(time>1)
    {
         //do something
         time=0;
    }
}

Coroutines have some overhead to them. State information is held for them much like a thread state is held by the operating system, so they can be intercepted (paused, stopped, however you like to think of it), then continued later.

That said, coroutines avoid the clutter in Update. Sometimes structure is more important for clarity and maintainability that raw performance.

Checking time in Update is lighter. It generates less code, runs faster and makes sense without having to understand how coroutines operate (coroutines are a Unity invention using C#, not a C# convention).

I personally prefer not to use coroutines. To me they seem a convenience for student or occasional programmers, and there are means of implementing that kind of notion with more feature. My position is based on the fact that I far prefer C++, and I’m familiar with techniques and design patterns I’ve used for years or decades.

So, where performance is paramount, the Update timer is a better choice. When clarity is paramount, the coroutine may be a better choice, but there are others.

The notion of calling a function after a delay (the ‘do something’ in your example) is a classic pattern repeated so often that it deserves its own machine to support it. There could be several timers for several subjects. This notion should be repeatable in many MonoBehaviour derivatives. To that extent, I’d suggest that ‘neither’ is a better answer to your question, because there’s one better.

I would create a class that can be instructed to call a function using a delegate after a time delay. Such a simple object can be a member, added to a list, shared and reused everywhere. Once the class is created (and, as many professionals do, added to one’s personal library of tools), using it is no more difficult than establishing a coroutine, but it can be used in Update without much clutter, and it could be used in a coroutine if desired. Usage is merely calling a function in this timer object to tell it what function to call, and when (or just when to call the function it is already configured for).

you should set time to 0 when it reaches 1. Otherwise, it will continue to count after it reaches one and the update will then act as a normal update. so void update(){ time += Time.delataTime; if(time > 1) { //do something time = 0;} } and when starting a Coroutine in the start function it will only run 1 time.