同样的for循环语句,在spring环境中执行和不在spring环境中执行,耗时不同。
@RestController
@RequestMapping("api/")
public class ApiV2Controller {
@RequestMapping(value = "upload")
public void upload() throws IOException {
for (int i = 0; i < 10; i++) {
long l = System.currentTimeMillis();
encode();
System.out.println("controller耗时:" + (System.currentTimeMillis() - l));
}
}
public static void main(String[] args) throws IOException {
for (int i = 0; i < 10; i++) {
long l = System.currentTimeMillis();
encode();
System.out.println("main耗时:" + (System.currentTimeMillis() - l));
}
}
private static void encode() throws IOException {
File file = new File("C:\\Users\\admin\\Desktop\\demo.bin");
byte[] fileBytes = Files.readAllBytes(file.toPath());
int index = 0;
byte[] key = "onekey;".getBytes(StandardCharsets.UTF_8);
int keylen = key.length;
int length = fileBytes.length;
for (int i = 0; i < length; i++) {
if (index >= keylen) {
index = 0;
}
int diff = fileBytes[i] - key[index];
if (diff < -128) {
diff += 256;
}
fileBytes[i] = (byte) diff;
index++;
}
}
代码的for循环是一个常用的用key加密文件的方法
在spring中执行耗时
controller耗时:399
controller耗时:368
controller耗时:367
controller耗时:366
controller耗时:368
controller耗时:367
controller耗时:367
controller耗时:367
controller耗时:367
controller耗时:367
使用普通的main方法耗时
main耗时:137
main耗时:118
main耗时:114
main耗时:114
main耗时:114
main耗时:116
main耗时:117
main耗时:118
main耗时:111
main耗时:113
spring中执行耗时会多2-3倍,文件大小为64Mb
很疑惑,不知道为什么会这样
求解答
环境差异很大。运行main函数和启动springboot时,jvm参数差别很大,这些差异都能影响到程序的执行性能。另外编译器在运行过程中会有一些优化,springboot和main中优化也会不一样。