Java的.replace()优化(重写)

本文介绍了通过改造Java的replace方法实现性能提升的案例。代码展示了一个自定义的StringUtils类,其中的replace方法利用StringBuffer提高替换操作效率。实测表明,对于长文本和高频替换字符,优化后的代码执行速度提升显著。请注意,实际使用时需谨慎测试以确保适用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说明:今天刚好看到一篇重写replace性能提升了10倍的文章,里面的replace方法改造我觉得挺有意思,而且性能提升很夸张,我一看就心动了,代码我做了下改造比较贴近我们常用的.replace()替换方法,直接上代码。

 

public class StringUtils {

	public static String replace(String content,String oldChar, String newChar){
		int beginIndex = 0;
		int endIndex = 0;
		StringBuffer stringBuffer = new StringBuffer();
		if(isNotEmpty(content)&&isNotEmpty(oldChar)){
			int len = oldChar.length();
			beginIndex = content.indexOf(oldChar,0);
			if(beginIndex>0){
				stringBuffer.append(content,0,beginIndex);
			}
			stringBuffer.append(newChar);
			while (beginIndex !=-1){
				endIndex = content.indexOf(oldChar,beginIndex+len);
				if(endIndex == -1){
					stringBuffer.append(content.substring(beginIndex+len));
					beginIndex=-1;
					continue;
				}
				stringBuffer.append(content,beginIndex+len,endIndex);
				stringBuffer.append(newChar);
				beginIndex = content.indexOf(oldChar,endIndex+len);
				if(beginIndex-endIndex>=1){
					stringBuffer.append(content,endIndex+len,beginIndex);
					stringBuffer.append(newChar);
				}
			}
			if(endIndex!=-1){
				stringBuffer.append(content.substring(endIndex+len));
			}
		}else{
			return content;
		}
		return stringBuffer.toString();
	}

	public static void main(String[] args) {
		String content = "这里文本内容尽量复杂,能看到效果更好,下面替换的字符串自行修改...";
		long s = System.currentTimeMillis();
		content.replace("的","滴").replace("我","你");
		long e = System.currentTimeMillis();
		//传统替换消耗时间
		System.out.println(e-s);
		replace(replace(content,"的","滴"),"我","你");
		//改写后替换消耗时间
		System.out.println(System.currentTimeMillis()-e);
	}
}

        这个优化效果还是挺强大的,比如上述main中的content内容越大,替换的字符串出现频次越多,执行后打印出来的时间基数差距越大,经测试content长度2000字符(2篇文章)替换同样的常见字符,打印出的耗时:前值 5 后值 2 

上述代码测试并未穷尽,开发过程中请谨慎使用

package com.xymzsfxy.backend.service; import com.xymzsfxy.backend.entity.PriceHistory; import com.xymzsfxy.backend.entity.Product; import com.xymzsfxy.backend.repository.PriceHistoryRepository; import com.xymzsfxy.backend.repository.ProductRepository; import lombok.extern.slf4j.Slf4j; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.Map; @Slf4j @Service public class PriceCrawlerService { private final ProductRepository productRepository; private final PriceHistoryRepository priceHistoryRepository; @Value("#{${crawler.sources}}") private Map<String, String> crawlerSources; @Value("#{${crawler.selectors}}") private Map<String, String> crawlerSelectors; @Autowired public PriceCrawlerService(ProductRepository productRepository, PriceHistoryRepository priceHistoryRepository) { this.productRepository = productRepository; this.priceHistoryRepository = priceHistoryRepository; } @Async("crawlerTaskExecutor") public void crawlPrices(Long productId) { Product product = productRepository.findById(productId) .orElseThrow(() -> new IllegalArgumentException("无效商品ID: " + productId)); crawlerSources.forEach((sourceName, urlTemplate) -> { try { String targetUrl = String.format(urlTemplate, product.getExternalId()); Document doc = Jsoup.connect(targetUrl) .timeout(10000) .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36") .get(); String selector = crawlerSelectors.get(sourceName); String priceText = doc.selectFirst(selector).text(); BigDecimal price = parsePrice(priceText); savePriceData(product, sourceName, price); } catch (IOException e) { log.error("[{}] 网络请求失败: {}", sourceName, e.getMessage()); } catch (Exception e) { log.error("[{}] 数据处理异常: {}", sourceName, e.getMessage()); } }); } private BigDecimal parsePrice(String priceText) { String numericPrice = priceText.replaceAll("[^\\d.,]", ""); return new BigDecimal(numericPrice.replace(",", "")); } @Transactional protected void savePriceData(Product product, String source, BigDecimal price) { // 保存价格记录 PriceHistory record = new PriceHistory(); record.setProductId(product.getId()); record.setSource(source); record.setPrice(price); record.setCrawlTime(LocalDateTime.now()); priceHistoryRepository.save(record); // 更新商品最新价格 product.setLatestPrice(price); product.setUpdatedTime(LocalDateTime.now()); productRepository.save(product); } }框架是springboot重写代码功能不变
最新发布
03-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值