TORONTO — For the Canadian leader, it was a rare poke at the United States.

Prime Minister Justin Trudeau was defending his government’s historic budget deficit, caused largely by shutting down parts of the economy and ramping up spending on emergency relief programs to fight the coronavirus.

Considering the alternative, he told reporters in Ottawa, it’s been worth it.

“We were able to control the virus better than many of our allies,” he told reporters this month. “Including, particularly, our neighbor.”

He has a point. Canada’s response to the pandemic hasn’t been perfect — Quebec and Ontario suffered substantial outbreaks, authorities enlisted soldiers to help in hard-hit long-term care facilities, and Mexico was so concerned about conditions on farms that it threatened to hold back its migrant workers.

Still, the country has fared far better than the United States. The close allies share similar connections to initial hot spots in China and Europe, and they confirmed their first cases within a week of each other in January. But the United States has since reported more than three times as many total infections per capita, and nearly twice as many deaths.

Canadians have taken note. The two countries agreed to close their shared border to nonessential travel in March. Surveys here show that the closure, while economically painful, continues to enjoy wide public support.

“There’s no smugness,” said Susy Hota, medical director of infection prevention and control at Toronto’s University Health Network. “We look at what’s happening to our neighbor in the south and all of us are just feeling really bad about it.”

Analysts point to several reasons for the divergent outcomes.

Canada has the natural advantage of geography: It has less than one-ninth the United States’ population. Canadians aren’t evenly distributed — two-thirds of them live within 62 miles of the U.S. border — but no city here is as densely populated as, say, New York City.

“We have that geographic distribution between major centers,” said Jason Kindrachuk, a virologist at the University of Manitoba. “Undoubtedly, it has played a role.”

But the country has also performed better at critical moments. In the early stages of the pandemic, Canada was able to ramp up testing more quickly than the United States, enabling it to better isolate the sick, trace contacts and limit spread.

Efforts in the United States were hindered in part by a flawed test.

Canada’s early success in testing would not last. Several provinces have struggled to meet testing targets and clear backlogs, leaving officials flying blind when trying to identify outbreaks or to rapidly trace contacts.

Zain Chagla, an infectious-diseases physician at St. Joseph’s Healthcare Hamilton, said some hospitals have turned away patients with coronavirus symptoms for lack of tests. The United States now tests more people per capita than Canada.

The Canadian people have been less divided and more disciplined. Some provinces and territories could have locked down sooner, analysts say, but once measures were announced, they were strict, broadly uniform and widely followed.

“It was completely unexpected,” said Gary Kobinger, director of the Research Center on Infectious Diseases at Quebec’s Laval University. “I thought that people would not accept to stay home. . . . This also helped.”

Some provinces and territories, like some U.S. states, moved early to limit travel from other parts of the country and mandate quarantines. Michael Gardam, chief of staff at Toronto’s Humber River Hospital, said provinces have mostly been “appropriately cautious” when easing restrictions, in contrast to those states that never imposed closures or stay-at-home orders or loosened controls prematurely.

Researchers at the University of Toronto studying reopenings found that restrictions in Yukon, a northern territory that had 11 coronavirus cases and no deaths, are more stringent than those in Texas, where hospitalizations are surging.

Gerald Evans, a professor of medicine at Queens University in Kingston, Ontario, said Canada’s single-payer national health-care system also confers “distinct” advantages, allowing people to seek care for covid-19, the disease caused by the coronavirus, without fear of out-of-pocket costs.

Analysts also point to differences in political leadership.

Canadian officials have largely set aside partisan grievances for a “Team Canada” effort. Alberta Premier Jason Kenney sent excess personal protective gear to provinces in need, including Quebec, led by frequent sparring partner Premier François Legault.

That contrasts with the response in the United States, where President Trump has at times seemed to condition federal aid on support for him, and governors have fought with each other and the federal government over critical supplies.

Though Canada’s response has not been entirely devoid of politics, Canadian officials have consistently deferred to public health experts and scientists to drive policy decisions and have offered a generally consistent message.

“There’s been a consensus . . . that covid-19 is a very serious health problem and many members of Parliament from all parties have been elevating the messages of health experts over the course of the crisis,” said Eric Merkley, a political scientist at the University of Toronto. “That distinguishes us from the United States, where the Republican Party has elevated covid skeptics quite substantially.”

Merkley is the lead author of a paper that describes Canada’s response as a “rare moment of cross-partisan consensus” among political elites and the public.

Canada’s performance has included missteps. Before the country recorded its first case, officials assured the public that the health-care system was ready and the risk posed by the virus was “low.”

They would repeat that message into early March. But as cases began to tick up in February, some infectious-disease experts worried that inertia had slowed the government’s response. Some said Canada was too slow to close its borders, screen travelers and enforce quarantines. Some provinces dispatched their own public health workers to airports to screen travelers, encroaching on an area of federal jurisdiction.

There were worries about shortages of personal protective equipment. Government efforts to procure supplies ran into barriers. The problem has not been entirely rectified. Chagla said his hospital still faces shortages of N95 respirator masks.

Long-term-care homes quickly emerged as hot spots. Roughly one-fifth of Canada’s cases and more than 80 percent of its deaths have occurred in those facilities, according to government figures, despite repeated warnings about their vulnerabilities.

Spiraling outbreaks in Ontario and Quebec were so severe that Ottawa agreed to send the Canadian military to help. Soldiers documented abuses including cockroach infestations, force feeding and “significant gross fecal contamination” in patients’ rooms.

Canada had nearly two decades to prepare for a pandemic.

In 2003, the severe acute respiratory syndrome, or SARS, killed 44 people in Toronto — the most deaths outside Asia.

A commission that reviewed the province’s response to the outbreak said the public health-care system was “broken, neglected, inadequate and dysfunctional.” In the next outbreak, it advised against waiting for scientific certainty before implementing measures to reduce risk.

Kobinger, who helped pioneer the Ebola vaccine, said the advice has not been followed, particularly with respect to guidance on masks. Canada recommended wearing masks many weeks after the United States, reversing an earlier position and confusing citizens, he said.

Gardam, who worked on the front lines of the 2003 outbreak, said he agreed at the outset of the coronavirus pandemic with the officials who said Canada had learned lessons from SARS — “only to find that some of the issues we had during SARS just sort of came up again.”

Chagla said now is not the time to be complacent. As of Tuesday evening, Canada had reported more than 110,000 cases of coronavirus, 20th in the world, and 8,843 deaths, according to data kept by Johns Hopkins. A Canadian Senate committee reported this month that the country is ill-prepared to handle a second wave.

“I think the Canadian mentality sometimes is to compare yourself to the Americans,” Chagla said. “I think we certainly can, but we can also look and see how could we have improved ourselves.”