The Joint United Nations Programme on HIV/AIDS (UNAIDS) updated the 95-95-95 targets for the HIV endgame in 2030. To achieve the first target in a timely manner, we investigate the optimized strategy of resource allocation to maximize timely HIV diagnosis in 14 populations in China. We developed a mathematical model by integrating epidemiological, demographical and behavioural data from 12 high-risk and two general populations to evaluate the impact of various resource allocation strategies of HIV testing on HIV incidence in China. We identified the optimized allocation strategy that maximizes the number of HIV diagnoses at an estimated total spending on HIV tests in China and calculated the per-capita cost of new HIV case detection. We estimated that 144,795 new HIV cases may occur annually in 14 populations in China, with a total annual spending of US$2.8 billion on HIV testing. The largest proportion of spending was allocated to general males (44.0%), followed by general females (42.6%) and pregnant women (5.1%). Despite this allocation strategy, only 45.5% (65,867/144,795, timely diagnosis rate) of annual new infections were diagnosed within a year of acquisition, with a cost of $42,852 required for each new HIV case detection. By optimizing the allocation of HIV testing resources within the same spending amount, we found that general females received the highest proportion of spending allocation (45.1%), followed by low-risk men who have sex with men (13.9%) and pregnant women (8.4%). In contrast, the proportion of spending allocation for the general males decreased to 0.2%. With this optimized strategy, we estimated that 120,755 (83.4%) of annual new infections would be diagnosed within a year of acquisition, with the cost required for one HIV case detection reduced to $23,364/case. Further spending increases could allow for significant increases in HIV testing among lower-risk populations. Optimizing resource allocation for HIV testing in high-risk populations would improve HIV timely diagnosis rate of new infections and reduce cost per HIV case detection.